1 //! Generalized type relating mechanism.
3 //! A type relation `R` relates a pair of values `(A, B)`. `A and B` are usually
4 //! types or regions but can be other things. Examples of type relations are
5 //! subtyping, type equality, etc.
7 use crate::mir::interpret::{get_slice_bytes, ConstValue, GlobalAlloc, Scalar};
8 use crate::ty::error::{ExpectedFound, TypeError};
9 use crate::ty::subst::{GenericArg, GenericArgKind, Subst, SubstsRef};
10 use crate::ty::{self, ImplSubject, Term, Ty, TyCtxt, TypeFoldable};
12 use rustc_hir::def_id::DefId;
13 use rustc_span::DUMMY_SP;
14 use rustc_target::spec::abi;
17 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
19 #[derive(Clone, Debug)]
21 ExistentialRegionBound, // relating an existential region bound
24 pub trait TypeRelation<'tcx>: Sized {
25 fn tcx(&self) -> TyCtxt<'tcx>;
27 fn param_env(&self) -> ty::ParamEnv<'tcx>;
29 /// Returns a static string we can use for printouts.
30 fn tag(&self) -> &'static str;
32 /// Returns `true` if the value `a` is the "expected" type in the
33 /// relation. Just affects error messages.
34 fn a_is_expected(&self) -> bool;
36 fn with_cause<F, R>(&mut self, _cause: Cause, f: F) -> R
38 F: FnOnce(&mut Self) -> R,
43 /// Generic relation routine suitable for most anything.
44 fn relate<T: Relate<'tcx>>(&mut self, a: T, b: T) -> RelateResult<'tcx, T> {
45 Relate::relate(self, a, b)
48 /// Relate the two substitutions for the given item. The default
49 /// is to look up the variance for the item and proceed
51 fn relate_item_substs(
54 a_subst: SubstsRef<'tcx>,
55 b_subst: SubstsRef<'tcx>,
56 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
58 "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
59 item_def_id, a_subst, b_subst
63 let opt_variances = tcx.variances_of(item_def_id);
64 relate_substs(self, Some((item_def_id, opt_variances)), a_subst, b_subst)
67 /// Switch variance for the purpose of relating `a` and `b`.
68 fn relate_with_variance<T: Relate<'tcx>>(
70 variance: ty::Variance,
71 info: ty::VarianceDiagInfo<'tcx>,
74 ) -> RelateResult<'tcx, T>;
76 // Overridable relations. You shouldn't typically call these
77 // directly, instead call `relate()`, which in turn calls
78 // these. This is both more uniform but also allows us to add
79 // additional hooks for other types in the future if needed
80 // without making older code, which called `relate`, obsolete.
82 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>;
88 ) -> RelateResult<'tcx, ty::Region<'tcx>>;
94 ) -> RelateResult<'tcx, ty::Const<'tcx>>;
98 a: ty::Binder<'tcx, T>,
99 b: ty::Binder<'tcx, T>,
100 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
105 pub trait Relate<'tcx>: TypeFoldable<'tcx> + Copy {
106 fn relate<R: TypeRelation<'tcx>>(
110 ) -> RelateResult<'tcx, Self>;
113 ///////////////////////////////////////////////////////////////////////////
116 pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>(
118 a: ty::TypeAndMut<'tcx>,
119 b: ty::TypeAndMut<'tcx>,
121 ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> {
122 debug!("{}.mts({:?}, {:?})", relation.tag(), a, b);
123 if a.mutbl != b.mutbl {
124 Err(TypeError::Mutability)
127 let (variance, info) = match mutbl {
128 ast::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None),
129 ast::Mutability::Mut => {
130 (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 })
133 let ty = relation.relate_with_variance(variance, info, a.ty, b.ty)?;
134 Ok(ty::TypeAndMut { ty, mutbl })
138 pub fn relate_substs<'tcx, R: TypeRelation<'tcx>>(
140 variances: Option<(DefId, &[ty::Variance])>,
141 a_subst: SubstsRef<'tcx>,
142 b_subst: SubstsRef<'tcx>,
143 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
144 let tcx = relation.tcx();
145 let mut cached_ty = None;
147 let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| {
148 let (variance, variance_info) = match variances {
149 Some((ty_def_id, variances)) => {
150 let variance = variances[i];
151 let variance_info = if variance == ty::Invariant {
153 .get_or_insert_with(|| tcx.type_of(ty_def_id).subst(tcx, a_subst));
154 ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() }
156 ty::VarianceDiagInfo::default()
158 (variance, variance_info)
160 None => (ty::Invariant, ty::VarianceDiagInfo::default()),
162 relation.relate_with_variance(variance, variance_info, a, b)
165 tcx.mk_substs(params)
168 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
169 fn relate<R: TypeRelation<'tcx>>(
173 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
174 let tcx = relation.tcx();
176 if a.c_variadic != b.c_variadic {
177 return Err(TypeError::VariadicMismatch(expected_found(
183 let unsafety = relation.relate(a.unsafety, b.unsafety)?;
184 let abi = relation.relate(a.abi, b.abi)?;
186 if a.inputs().len() != b.inputs().len() {
187 return Err(TypeError::ArgCount);
190 let inputs_and_output = iter::zip(a.inputs(), b.inputs())
191 .map(|(&a, &b)| ((a, b), false))
192 .chain(iter::once(((a.output(), b.output()), true)))
193 .map(|((a, b), is_output)| {
195 relation.relate(a, b)
197 relation.relate_with_variance(
199 ty::VarianceDiagInfo::default(),
206 .map(|(i, r)| match r {
207 Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
208 Err(TypeError::ArgumentSorts(exp_found, i))
210 Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
211 Err(TypeError::ArgumentMutability(i))
216 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
217 c_variadic: a.c_variadic,
224 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
225 fn relate<R: TypeRelation<'tcx>>(
227 a: ty::BoundConstness,
228 b: ty::BoundConstness,
229 ) -> RelateResult<'tcx, ty::BoundConstness> {
231 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
238 impl<'tcx> Relate<'tcx> for ast::Unsafety {
239 fn relate<R: TypeRelation<'tcx>>(
243 ) -> RelateResult<'tcx, ast::Unsafety> {
245 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
252 impl<'tcx> Relate<'tcx> for abi::Abi {
253 fn relate<R: TypeRelation<'tcx>>(
257 ) -> RelateResult<'tcx, abi::Abi> {
258 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
262 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
263 fn relate<R: TypeRelation<'tcx>>(
265 a: ty::ProjectionTy<'tcx>,
266 b: ty::ProjectionTy<'tcx>,
267 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
268 if a.item_def_id != b.item_def_id {
269 Err(TypeError::ProjectionMismatched(expected_found(
275 let substs = relation.relate(a.substs, b.substs)?;
276 Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
281 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
282 fn relate<R: TypeRelation<'tcx>>(
284 a: ty::ExistentialProjection<'tcx>,
285 b: ty::ExistentialProjection<'tcx>,
286 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
287 if a.item_def_id != b.item_def_id {
288 Err(TypeError::ProjectionMismatched(expected_found(
294 let term = relation.relate_with_variance(
296 ty::VarianceDiagInfo::default(),
300 let substs = relation.relate_with_variance(
302 ty::VarianceDiagInfo::default(),
306 Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, term })
311 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
312 fn relate<R: TypeRelation<'tcx>>(
314 a: ty::TraitRef<'tcx>,
315 b: ty::TraitRef<'tcx>,
316 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
317 // Different traits cannot be related.
318 if a.def_id != b.def_id {
319 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
321 let substs = relate_substs(relation, None, a.substs, b.substs)?;
322 Ok(ty::TraitRef { def_id: a.def_id, substs })
327 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
328 fn relate<R: TypeRelation<'tcx>>(
330 a: ty::ExistentialTraitRef<'tcx>,
331 b: ty::ExistentialTraitRef<'tcx>,
332 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
333 // Different traits cannot be related.
334 if a.def_id != b.def_id {
335 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
337 let substs = relate_substs(relation, None, a.substs, b.substs)?;
338 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
343 #[derive(Copy, Debug, Clone, TypeFoldable)]
344 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
346 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
347 fn relate<R: TypeRelation<'tcx>>(
349 a: GeneratorWitness<'tcx>,
350 b: GeneratorWitness<'tcx>,
351 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
352 assert_eq!(a.0.len(), b.0.len());
353 let tcx = relation.tcx();
354 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
355 Ok(GeneratorWitness(types))
359 impl<'tcx> Relate<'tcx> for ImplSubject<'tcx> {
361 fn relate<R: TypeRelation<'tcx>>(
363 a: ImplSubject<'tcx>,
364 b: ImplSubject<'tcx>,
365 ) -> RelateResult<'tcx, ImplSubject<'tcx>> {
367 (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
368 let trait_ref = ty::TraitRef::relate(relation, trait_ref_a, trait_ref_b)?;
369 Ok(ImplSubject::Trait(trait_ref))
371 (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
372 let ty = Ty::relate(relation, ty_a, ty_b)?;
373 Ok(ImplSubject::Inherent(ty))
375 (ImplSubject::Trait(_), ImplSubject::Inherent(_))
376 | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
377 bug!("can not relate TraitRef and Ty");
383 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
385 fn relate<R: TypeRelation<'tcx>>(
389 ) -> RelateResult<'tcx, Ty<'tcx>> {
394 /// The main "type relation" routine. Note that this does not handle
395 /// inference artifacts, so you should filter those out before calling
397 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
401 ) -> RelateResult<'tcx, Ty<'tcx>> {
402 let tcx = relation.tcx();
403 debug!("super_relate_tys: a={:?} b={:?}", a, b);
404 match (a.kind(), b.kind()) {
405 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
406 // The caller should handle these cases!
407 bug!("var types encountered in super_relate_tys")
410 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
411 bug!("bound types encountered in super_relate_tys")
414 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
428 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
430 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
432 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
433 let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
434 Ok(tcx.mk_adt(a_def, substs))
437 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
439 (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
440 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
441 relation.relate_with_variance(
443 ty::VarianceDiagInfo::default(),
448 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
451 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
454 // All Generator types with the same id represent
455 // the (anonymous) type of the same generator expression. So
456 // all of their regions should be equated.
457 let substs = relation.relate(a_substs, b_substs)?;
458 Ok(tcx.mk_generator(a_id, substs, movability))
461 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
462 // Wrap our types with a temporary GeneratorWitness struct
463 // inside the binder so we can related them
464 let a_types = a_types.map_bound(GeneratorWitness);
465 let b_types = b_types.map_bound(GeneratorWitness);
466 // Then remove the GeneratorWitness for the result
467 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
468 Ok(tcx.mk_generator_witness(types))
471 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
472 // All Closure types with the same id represent
473 // the (anonymous) type of the same closure expression. So
474 // all of their regions should be equated.
475 let substs = relation.relate(a_substs, b_substs)?;
476 Ok(tcx.mk_closure(a_id, &substs))
479 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
480 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
484 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
485 let r = relation.relate_with_variance(
487 ty::VarianceDiagInfo::default(),
491 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
492 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
493 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
494 Ok(tcx.mk_ref(r, mt))
497 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
498 let t = relation.relate(a_t, b_t)?;
499 match relation.relate(sz_a, sz_b) {
500 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
502 // Check whether the lengths are both concrete/known values,
503 // but are unequal, for better diagnostics.
505 // It might seem dubious to eagerly evaluate these constants here,
506 // we however cannot end up with errors in `Relate` during both
507 // `type_of` and `predicates_of`. This means that evaluating the
508 // constants should not cause cycle errors here.
509 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
510 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
512 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
513 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
521 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
522 let t = relation.relate(a_t, b_t)?;
526 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
527 if as_.len() == bs.len() {
528 Ok(tcx.mk_tup(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
529 } else if !(as_.is_empty() || bs.is_empty()) {
530 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
532 Err(TypeError::Sorts(expected_found(relation, a, b)))
536 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
537 if a_def_id == b_def_id =>
539 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
540 Ok(tcx.mk_fn_def(a_def_id, substs))
543 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
544 let fty = relation.relate(a_fty, b_fty)?;
545 Ok(tcx.mk_fn_ptr(fty))
548 // these two are already handled downstream in case of lazy normalization
549 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
550 let projection_ty = relation.relate(a_data, b_data)?;
551 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
554 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
555 if a_def_id == b_def_id =>
557 let substs = relate_substs(relation, None, a_substs, b_substs)?;
558 Ok(tcx.mk_opaque(a_def_id, substs))
561 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
565 /// The main "const relation" routine. Note that this does not handle
566 /// inference artifacts, so you should filter those out before calling
568 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
572 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
573 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
574 let tcx = relation.tcx();
576 // FIXME(oli-obk): once const generics can have generic types, this assertion
577 // will likely get triggered. Move to `normalize_erasing_regions` at that point.
578 let a_ty = tcx.erase_regions(a.ty());
579 let b_ty = tcx.erase_regions(b.ty());
581 relation.tcx().sess.delay_span_bug(
583 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
587 let eagerly_eval = |x: ty::Const<'tcx>| x.eval(tcx, relation.param_env());
588 let a = eagerly_eval(a);
589 let b = eagerly_eval(b);
591 // Currently, the values that can be unified are primitive types,
592 // and those that derive both `PartialEq` and `Eq`, corresponding
593 // to structural-match types.
594 let is_match = match (a.val(), b.val()) {
595 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
596 // The caller should handle these cases!
597 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
600 (ty::ConstKind::Error(_), _) => return Ok(a),
601 (_, ty::ConstKind::Error(_)) => return Ok(b),
603 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
604 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
605 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
606 check_const_value_eq(relation, a_val, b_val, a, b)?
609 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
610 if tcx.features().generic_const_exprs =>
612 tcx.try_unify_abstract_consts(relation.param_env().and((au.shrink(), bu.shrink())))
615 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
616 // and is the better alternative to waiting until `generic_const_exprs` can
618 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
619 if au.def == bu.def && au.promoted == bu.promoted =>
621 let substs = relation.relate_with_variance(
622 ty::Variance::Invariant,
623 ty::VarianceDiagInfo::default(),
627 return Ok(tcx.mk_const(ty::ConstS {
628 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
631 promoted: au.promoted,
638 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
641 fn check_const_value_eq<'tcx, R: TypeRelation<'tcx>>(
643 a_val: ConstValue<'tcx>,
644 b_val: ConstValue<'tcx>,
645 // FIXME(oli-obk): these arguments should go away with valtrees
648 // FIXME(oli-obk): this should just be `bool` with valtrees
649 ) -> RelateResult<'tcx, bool> {
650 let tcx = relation.tcx();
651 Ok(match (a_val, b_val) {
652 (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
656 ConstValue::Scalar(Scalar::Ptr(a_val, _a_size)),
657 ConstValue::Scalar(Scalar::Ptr(b_val, _b_size)),
660 || match (tcx.global_alloc(a_val.provenance), tcx.global_alloc(b_val.provenance)) {
661 (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
662 a_instance == b_instance
668 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
669 get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
672 (ConstValue::ByRef { alloc: alloc_a, .. }, ConstValue::ByRef { alloc: alloc_b, .. })
673 if a.ty().is_ref() || b.ty().is_ref() =>
675 if a.ty().is_ref() && b.ty().is_ref() {
681 (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
682 let a_destructured = tcx.destructure_const(relation.param_env().and(a));
683 let b_destructured = tcx.destructure_const(relation.param_env().and(b));
685 // Both the variant and each field have to be equal.
686 if a_destructured.variant == b_destructured.variant {
687 for (a_field, b_field) in iter::zip(a_destructured.fields, b_destructured.fields) {
688 relation.consts(*a_field, *b_field)?;
701 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> {
702 fn relate<R: TypeRelation<'tcx>>(
706 ) -> RelateResult<'tcx, Self> {
707 let tcx = relation.tcx();
709 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
710 // We need to perform this deduplication as we sometimes generate duplicate projections
712 let mut a_v: Vec<_> = a.into_iter().collect();
713 let mut b_v: Vec<_> = b.into_iter().collect();
714 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
715 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
717 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
719 if a_v.len() != b_v.len() {
720 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
723 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
724 use crate::ty::ExistentialPredicate::*;
725 match (ep_a.skip_binder(), ep_b.skip_binder()) {
726 (Trait(a), Trait(b)) => Ok(ep_a
727 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
728 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
729 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
731 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
732 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
735 tcx.mk_poly_existential_predicates(v)
739 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
740 fn relate<R: TypeRelation<'tcx>>(
742 a: ty::ClosureSubsts<'tcx>,
743 b: ty::ClosureSubsts<'tcx>,
744 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
745 let substs = relate_substs(relation, None, a.substs, b.substs)?;
746 Ok(ty::ClosureSubsts { substs })
750 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
751 fn relate<R: TypeRelation<'tcx>>(
753 a: ty::GeneratorSubsts<'tcx>,
754 b: ty::GeneratorSubsts<'tcx>,
755 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
756 let substs = relate_substs(relation, None, a.substs, b.substs)?;
757 Ok(ty::GeneratorSubsts { substs })
761 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
762 fn relate<R: TypeRelation<'tcx>>(
766 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
767 relate_substs(relation, None, a, b)
771 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
772 fn relate<R: TypeRelation<'tcx>>(
776 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
777 relation.regions(a, b)
781 impl<'tcx> Relate<'tcx> for ty::Const<'tcx> {
782 fn relate<R: TypeRelation<'tcx>>(
786 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
787 relation.consts(a, b)
791 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
792 fn relate<R: TypeRelation<'tcx>>(
794 a: ty::Binder<'tcx, T>,
795 b: ty::Binder<'tcx, T>,
796 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
797 relation.binders(a, b)
801 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
802 fn relate<R: TypeRelation<'tcx>>(
806 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
807 match (a.unpack(), b.unpack()) {
808 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
809 Ok(relation.relate(a_lt, b_lt)?.into())
811 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
812 Ok(relation.relate(a_ty, b_ty)?.into())
814 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
815 Ok(relation.relate(a_ct, b_ct)?.into())
817 (GenericArgKind::Lifetime(unpacked), x) => {
818 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
820 (GenericArgKind::Type(unpacked), x) => {
821 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
823 (GenericArgKind::Const(unpacked), x) => {
824 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
830 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
831 fn relate<R: TypeRelation<'tcx>>(
835 ) -> RelateResult<'tcx, ty::ImplPolarity> {
837 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
844 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
845 fn relate<R: TypeRelation<'tcx>>(
847 a: ty::TraitPredicate<'tcx>,
848 b: ty::TraitPredicate<'tcx>,
849 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
850 Ok(ty::TraitPredicate {
851 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
852 constness: relation.relate(a.constness, b.constness)?,
853 polarity: relation.relate(a.polarity, b.polarity)?,
858 impl<'tcx> Relate<'tcx> for ty::Term<'tcx> {
859 fn relate<R: TypeRelation<'tcx>>(
863 ) -> RelateResult<'tcx, Self> {
865 (Term::Ty(a), Term::Ty(b)) => relation.relate(a, b)?.into(),
866 (Term::Const(a), Term::Const(b)) => relation.relate(a, b)?.into(),
867 _ => return Err(TypeError::Mismatch),
872 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
873 fn relate<R: TypeRelation<'tcx>>(
875 a: ty::ProjectionPredicate<'tcx>,
876 b: ty::ProjectionPredicate<'tcx>,
877 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
878 Ok(ty::ProjectionPredicate {
879 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
880 term: relation.relate(a.term, b.term)?,
885 ///////////////////////////////////////////////////////////////////////////
888 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
890 R: TypeRelation<'tcx>,
892 ExpectedFound::new(relation.a_is_expected(), a, b)