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, 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>>;
92 a: &'tcx ty::Const<'tcx>,
93 b: &'tcx ty::Const<'tcx>,
94 ) -> RelateResult<'tcx, &'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 cached_ty.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 ty = 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, ty })
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 Ty<'tcx> {
361 fn relate<R: TypeRelation<'tcx>>(
365 ) -> RelateResult<'tcx, Ty<'tcx>> {
370 /// The main "type relation" routine. Note that this does not handle
371 /// inference artifacts, so you should filter those out before calling
373 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
377 ) -> RelateResult<'tcx, Ty<'tcx>> {
378 let tcx = relation.tcx();
379 debug!("super_relate_tys: a={:?} b={:?}", a, b);
380 match (a.kind(), b.kind()) {
381 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
382 // The caller should handle these cases!
383 bug!("var types encountered in super_relate_tys")
386 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
387 bug!("bound types encountered in super_relate_tys")
390 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
404 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
406 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
408 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
409 let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
410 Ok(tcx.mk_adt(a_def, substs))
413 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
415 (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
416 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
417 relation.relate_with_variance(
419 ty::VarianceDiagInfo::default(),
424 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
427 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
430 // All Generator types with the same id represent
431 // the (anonymous) type of the same generator expression. So
432 // all of their regions should be equated.
433 let substs = relation.relate(a_substs, b_substs)?;
434 Ok(tcx.mk_generator(a_id, substs, movability))
437 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
438 // Wrap our types with a temporary GeneratorWitness struct
439 // inside the binder so we can related them
440 let a_types = a_types.map_bound(GeneratorWitness);
441 let b_types = b_types.map_bound(GeneratorWitness);
442 // Then remove the GeneratorWitness for the result
443 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
444 Ok(tcx.mk_generator_witness(types))
447 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
448 // All Closure types with the same id represent
449 // the (anonymous) type of the same closure expression. So
450 // all of their regions should be equated.
451 let substs = relation.relate(a_substs, b_substs)?;
452 Ok(tcx.mk_closure(a_id, &substs))
455 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
456 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
460 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
461 let r = relation.relate_with_variance(
463 ty::VarianceDiagInfo::default(),
467 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
468 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
469 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
470 Ok(tcx.mk_ref(r, mt))
473 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
474 let t = relation.relate(a_t, b_t)?;
475 match relation.relate(sz_a, sz_b) {
476 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
478 // Check whether the lengths are both concrete/known values,
479 // but are unequal, for better diagnostics.
481 // It might seem dubious to eagerly evaluate these constants here,
482 // we however cannot end up with errors in `Relate` during both
483 // `type_of` and `predicates_of`. This means that evaluating the
484 // constants should not cause cycle errors here.
485 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
486 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
488 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
489 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
497 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
498 let t = relation.relate(a_t, b_t)?;
502 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
503 if as_.len() == bs.len() {
505 iter::zip(as_, bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())),
507 } else if !(as_.is_empty() || bs.is_empty()) {
508 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
510 Err(TypeError::Sorts(expected_found(relation, a, b)))
514 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
515 if a_def_id == b_def_id =>
517 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
518 Ok(tcx.mk_fn_def(a_def_id, substs))
521 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
522 let fty = relation.relate(a_fty, b_fty)?;
523 Ok(tcx.mk_fn_ptr(fty))
526 // these two are already handled downstream in case of lazy normalization
527 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
528 let projection_ty = relation.relate(a_data, b_data)?;
529 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
532 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
533 if a_def_id == b_def_id =>
535 let substs = relate_substs(relation, None, a_substs, b_substs)?;
536 Ok(tcx.mk_opaque(a_def_id, substs))
539 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
543 /// The main "const relation" routine. Note that this does not handle
544 /// inference artifacts, so you should filter those out before calling
546 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
548 a: &'tcx ty::Const<'tcx>,
549 b: &'tcx ty::Const<'tcx>,
550 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
551 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
552 let tcx = relation.tcx();
554 // FIXME(oli-obk): once const generics can have generic types, this assertion
555 // will likely get triggered. Move to `normalize_erasing_regions` at that point.
556 let a_ty = tcx.erase_regions(a.ty);
557 let b_ty = tcx.erase_regions(b.ty);
559 relation.tcx().sess.delay_span_bug(
561 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
565 let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env());
566 let a = eagerly_eval(a);
567 let b = eagerly_eval(b);
569 // Currently, the values that can be unified are primitive types,
570 // and those that derive both `PartialEq` and `Eq`, corresponding
571 // to structural-match types.
572 let is_match = match (a.val, b.val) {
573 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
574 // The caller should handle these cases!
575 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
578 (ty::ConstKind::Error(_), _) => return Ok(a),
579 (_, ty::ConstKind::Error(_)) => return Ok(b),
581 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
582 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
583 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
584 check_const_value_eq(relation, a_val, b_val, a, b)?
587 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
588 if tcx.features().generic_const_exprs =>
590 tcx.try_unify_abstract_consts((au.shrink(), bu.shrink()))
593 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
594 // and is the better alternative to waiting until `generic_const_exprs` can
596 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
597 if au.def == bu.def && au.promoted == bu.promoted =>
599 let substs = relation.relate_with_variance(
600 ty::Variance::Invariant,
601 ty::VarianceDiagInfo::default(),
605 return Ok(tcx.mk_const(ty::Const {
606 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
609 promoted: au.promoted,
616 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
619 fn check_const_value_eq<'tcx, R: TypeRelation<'tcx>>(
621 a_val: ConstValue<'tcx>,
622 b_val: ConstValue<'tcx>,
623 // FIXME(oli-obk): these arguments should go away with valtrees
624 a: &'tcx ty::Const<'tcx>,
625 b: &'tcx ty::Const<'tcx>,
626 // FIXME(oli-obk): this should just be `bool` with valtrees
627 ) -> RelateResult<'tcx, bool> {
628 let tcx = relation.tcx();
629 Ok(match (a_val, b_val) {
630 (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
634 ConstValue::Scalar(Scalar::Ptr(a_val, _a_size)),
635 ConstValue::Scalar(Scalar::Ptr(b_val, _b_size)),
638 || match (tcx.global_alloc(a_val.provenance), tcx.global_alloc(b_val.provenance)) {
639 (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
640 a_instance == b_instance
646 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
647 get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
650 (ConstValue::ByRef { alloc: alloc_a, .. }, ConstValue::ByRef { alloc: alloc_b, .. })
651 if a.ty.is_ref() || b.ty.is_ref() =>
653 if a.ty.is_ref() && b.ty.is_ref() {
659 (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
660 let a_destructured = tcx.destructure_const(relation.param_env().and(a));
661 let b_destructured = tcx.destructure_const(relation.param_env().and(b));
663 // Both the variant and each field have to be equal.
664 if a_destructured.variant == b_destructured.variant {
665 for (a_field, b_field) in iter::zip(a_destructured.fields, b_destructured.fields) {
666 relation.consts(a_field, b_field)?;
679 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> {
680 fn relate<R: TypeRelation<'tcx>>(
684 ) -> RelateResult<'tcx, Self> {
685 let tcx = relation.tcx();
687 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
688 // We need to perform this deduplication as we sometimes generate duplicate projections
690 let mut a_v: Vec<_> = a.into_iter().collect();
691 let mut b_v: Vec<_> = b.into_iter().collect();
692 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
693 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
695 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
697 if a_v.len() != b_v.len() {
698 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
701 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
702 use crate::ty::ExistentialPredicate::*;
703 match (ep_a.skip_binder(), ep_b.skip_binder()) {
704 (Trait(a), Trait(b)) => Ok(ep_a
705 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
706 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
707 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
709 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
710 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
713 tcx.mk_poly_existential_predicates(v)
717 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
718 fn relate<R: TypeRelation<'tcx>>(
720 a: ty::ClosureSubsts<'tcx>,
721 b: ty::ClosureSubsts<'tcx>,
722 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
723 let substs = relate_substs(relation, None, a.substs, b.substs)?;
724 Ok(ty::ClosureSubsts { substs })
728 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
729 fn relate<R: TypeRelation<'tcx>>(
731 a: ty::GeneratorSubsts<'tcx>,
732 b: ty::GeneratorSubsts<'tcx>,
733 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
734 let substs = relate_substs(relation, None, a.substs, b.substs)?;
735 Ok(ty::GeneratorSubsts { substs })
739 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
740 fn relate<R: TypeRelation<'tcx>>(
744 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
745 relate_substs(relation, None, a, b)
749 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
750 fn relate<R: TypeRelation<'tcx>>(
754 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
755 relation.regions(a, b)
759 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
760 fn relate<R: TypeRelation<'tcx>>(
762 a: &'tcx ty::Const<'tcx>,
763 b: &'tcx ty::Const<'tcx>,
764 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
765 relation.consts(a, b)
769 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
770 fn relate<R: TypeRelation<'tcx>>(
772 a: ty::Binder<'tcx, T>,
773 b: ty::Binder<'tcx, T>,
774 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
775 relation.binders(a, b)
779 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
780 fn relate<R: TypeRelation<'tcx>>(
784 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
785 match (a.unpack(), b.unpack()) {
786 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
787 Ok(relation.relate(a_lt, b_lt)?.into())
789 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
790 Ok(relation.relate(a_ty, b_ty)?.into())
792 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
793 Ok(relation.relate(a_ct, b_ct)?.into())
795 (GenericArgKind::Lifetime(unpacked), x) => {
796 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
798 (GenericArgKind::Type(unpacked), x) => {
799 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
801 (GenericArgKind::Const(unpacked), x) => {
802 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
808 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
809 fn relate<R: TypeRelation<'tcx>>(
813 ) -> RelateResult<'tcx, ty::ImplPolarity> {
815 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
822 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
823 fn relate<R: TypeRelation<'tcx>>(
825 a: ty::TraitPredicate<'tcx>,
826 b: ty::TraitPredicate<'tcx>,
827 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
828 Ok(ty::TraitPredicate {
829 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
830 constness: relation.relate(a.constness, b.constness)?,
831 polarity: relation.relate(a.polarity, b.polarity)?,
836 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
837 fn relate<R: TypeRelation<'tcx>>(
839 a: ty::ProjectionPredicate<'tcx>,
840 b: ty::ProjectionPredicate<'tcx>,
841 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
842 Ok(ty::ProjectionPredicate {
843 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
844 ty: relation.relate(a.ty, b.ty)?,
849 ///////////////////////////////////////////////////////////////////////////
852 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
854 R: TypeRelation<'tcx>,
856 ExpectedFound::new(relation.a_is_expected(), a, b)