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, 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
62 let opt_variances = self.tcx().variances_of(item_def_id);
63 relate_substs(self, Some(opt_variances), a_subst, b_subst)
66 /// Switch variance for the purpose of relating `a` and `b`.
67 fn relate_with_variance<T: Relate<'tcx>>(
69 variance: ty::Variance,
70 info: ty::VarianceDiagInfo<'tcx>,
73 ) -> RelateResult<'tcx, T>;
75 // Overridable relations. You shouldn't typically call these
76 // directly, instead call `relate()`, which in turn calls
77 // these. This is both more uniform but also allows us to add
78 // additional hooks for other types in the future if needed
79 // without making older code, which called `relate`, obsolete.
81 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>;
87 ) -> RelateResult<'tcx, ty::Region<'tcx>>;
91 a: &'tcx ty::Const<'tcx>,
92 b: &'tcx ty::Const<'tcx>,
93 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>;
97 a: ty::Binder<'tcx, T>,
98 b: ty::Binder<'tcx, T>,
99 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
104 pub trait Relate<'tcx>: TypeFoldable<'tcx> + Copy {
105 fn relate<R: TypeRelation<'tcx>>(
109 ) -> RelateResult<'tcx, Self>;
112 ///////////////////////////////////////////////////////////////////////////
115 pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>(
117 a: ty::TypeAndMut<'tcx>,
118 b: ty::TypeAndMut<'tcx>,
119 kind: ty::VarianceDiagMutKind,
120 ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> {
121 debug!("{}.mts({:?}, {:?})", relation.tag(), a, b);
122 if a.mutbl != b.mutbl {
123 Err(TypeError::Mutability)
126 let (variance, info) = match mutbl {
127 ast::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None),
128 ast::Mutability::Mut => (ty::Invariant, ty::VarianceDiagInfo::Mut { kind, ty: a.ty }),
130 let ty = relation.relate_with_variance(variance, info, a.ty, b.ty)?;
131 Ok(ty::TypeAndMut { ty, mutbl })
135 pub fn relate_substs<R: TypeRelation<'tcx>>(
137 variances: Option<&[ty::Variance]>,
138 a_subst: SubstsRef<'tcx>,
139 b_subst: SubstsRef<'tcx>,
140 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
141 let tcx = relation.tcx();
143 let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| {
144 let variance = variances.map_or(ty::Invariant, |v| v[i]);
145 relation.relate_with_variance(variance, ty::VarianceDiagInfo::default(), a, b)
148 tcx.mk_substs(params)
151 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
152 fn relate<R: TypeRelation<'tcx>>(
156 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
157 let tcx = relation.tcx();
159 if a.c_variadic != b.c_variadic {
160 return Err(TypeError::VariadicMismatch(expected_found(
166 let unsafety = relation.relate(a.unsafety, b.unsafety)?;
167 let abi = relation.relate(a.abi, b.abi)?;
169 if a.inputs().len() != b.inputs().len() {
170 return Err(TypeError::ArgCount);
173 let inputs_and_output = iter::zip(a.inputs(), b.inputs())
174 .map(|(&a, &b)| ((a, b), false))
175 .chain(iter::once(((a.output(), b.output()), true)))
176 .map(|((a, b), is_output)| {
178 relation.relate(a, b)
180 relation.relate_with_variance(
182 ty::VarianceDiagInfo::default(),
189 .map(|(i, r)| match r {
190 Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
191 Err(TypeError::ArgumentSorts(exp_found, i))
193 Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
194 Err(TypeError::ArgumentMutability(i))
199 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
200 c_variadic: a.c_variadic,
207 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
208 fn relate<R: TypeRelation<'tcx>>(
210 a: ty::BoundConstness,
211 b: ty::BoundConstness,
212 ) -> RelateResult<'tcx, ty::BoundConstness> {
214 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
221 impl<'tcx> Relate<'tcx> for ast::Unsafety {
222 fn relate<R: TypeRelation<'tcx>>(
226 ) -> RelateResult<'tcx, ast::Unsafety> {
228 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
235 impl<'tcx> Relate<'tcx> for abi::Abi {
236 fn relate<R: TypeRelation<'tcx>>(
240 ) -> RelateResult<'tcx, abi::Abi> {
241 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
245 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
246 fn relate<R: TypeRelation<'tcx>>(
248 a: ty::ProjectionTy<'tcx>,
249 b: ty::ProjectionTy<'tcx>,
250 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
251 if a.item_def_id != b.item_def_id {
252 Err(TypeError::ProjectionMismatched(expected_found(
258 let substs = relation.relate(a.substs, b.substs)?;
259 Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
264 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
265 fn relate<R: TypeRelation<'tcx>>(
267 a: ty::ExistentialProjection<'tcx>,
268 b: ty::ExistentialProjection<'tcx>,
269 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
270 if a.item_def_id != b.item_def_id {
271 Err(TypeError::ProjectionMismatched(expected_found(
277 let ty = relation.relate_with_variance(
279 ty::VarianceDiagInfo::default(),
283 let substs = relation.relate_with_variance(
285 ty::VarianceDiagInfo::default(),
289 Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, ty })
294 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
295 fn relate<R: TypeRelation<'tcx>>(
297 a: ty::TraitRef<'tcx>,
298 b: ty::TraitRef<'tcx>,
299 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
300 // Different traits cannot be related.
301 if a.def_id != b.def_id {
302 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
304 let substs = relate_substs(relation, None, a.substs, b.substs)?;
305 Ok(ty::TraitRef { def_id: a.def_id, substs })
310 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
311 fn relate<R: TypeRelation<'tcx>>(
313 a: ty::ExistentialTraitRef<'tcx>,
314 b: ty::ExistentialTraitRef<'tcx>,
315 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
316 // Different traits cannot be related.
317 if a.def_id != b.def_id {
318 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
320 let substs = relate_substs(relation, None, a.substs, b.substs)?;
321 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
326 #[derive(Copy, Debug, Clone, TypeFoldable)]
327 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
329 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
330 fn relate<R: TypeRelation<'tcx>>(
332 a: GeneratorWitness<'tcx>,
333 b: GeneratorWitness<'tcx>,
334 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
335 assert_eq!(a.0.len(), b.0.len());
336 let tcx = relation.tcx();
337 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
338 Ok(GeneratorWitness(types))
342 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
344 fn relate<R: TypeRelation<'tcx>>(
348 ) -> RelateResult<'tcx, Ty<'tcx>> {
353 /// The main "type relation" routine. Note that this does not handle
354 /// inference artifacts, so you should filter those out before calling
356 pub fn super_relate_tys<R: TypeRelation<'tcx>>(
360 ) -> RelateResult<'tcx, Ty<'tcx>> {
361 let tcx = relation.tcx();
362 debug!("super_relate_tys: a={:?} b={:?}", a, b);
363 match (a.kind(), b.kind()) {
364 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
365 // The caller should handle these cases!
366 bug!("var types encountered in super_relate_tys")
369 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
370 bug!("bound types encountered in super_relate_tys")
373 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
387 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
389 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
391 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
392 let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
393 Ok(tcx.mk_adt(a_def, substs))
396 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
398 (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
399 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
400 relation.relate_with_variance(
402 ty::VarianceDiagInfo::default(),
407 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
410 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
413 // All Generator types with the same id represent
414 // the (anonymous) type of the same generator expression. So
415 // all of their regions should be equated.
416 let substs = relation.relate(a_substs, b_substs)?;
417 Ok(tcx.mk_generator(a_id, substs, movability))
420 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
421 // Wrap our types with a temporary GeneratorWitness struct
422 // inside the binder so we can related them
423 let a_types = a_types.map_bound(GeneratorWitness);
424 let b_types = b_types.map_bound(GeneratorWitness);
425 // Then remove the GeneratorWitness for the result
426 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
427 Ok(tcx.mk_generator_witness(types))
430 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
431 // All Closure types with the same id represent
432 // the (anonymous) type of the same closure expression. So
433 // all of their regions should be equated.
434 let substs = relation.relate(a_substs, b_substs)?;
435 Ok(tcx.mk_closure(a_id, &substs))
438 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
439 let mt = relate_type_and_mut(relation, a_mt, b_mt, ty::VarianceDiagMutKind::RawPtr)?;
443 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
444 let r = relation.relate_with_variance(
446 ty::VarianceDiagInfo::default(),
450 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
451 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
452 let mt = relate_type_and_mut(relation, a_mt, b_mt, ty::VarianceDiagMutKind::Ref)?;
453 Ok(tcx.mk_ref(r, mt))
456 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
457 let t = relation.relate(a_t, b_t)?;
458 match relation.relate(sz_a, sz_b) {
459 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
461 // Check whether the lengths are both concrete/known values,
462 // but are unequal, for better diagnostics.
464 // It might seem dubious to eagerly evaluate these constants here,
465 // we however cannot end up with errors in `Relate` during both
466 // `type_of` and `predicates_of`. This means that evaluating the
467 // constants should not cause cycle errors here.
468 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
469 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
471 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
472 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
480 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
481 let t = relation.relate(a_t, b_t)?;
485 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
486 if as_.len() == bs.len() {
488 iter::zip(as_, bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())),
490 } else if !(as_.is_empty() || bs.is_empty()) {
491 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
493 Err(TypeError::Sorts(expected_found(relation, a, b)))
497 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
498 if a_def_id == b_def_id =>
500 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
501 Ok(tcx.mk_fn_def(a_def_id, substs))
504 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
505 let fty = relation.relate(a_fty, b_fty)?;
506 Ok(tcx.mk_fn_ptr(fty))
509 // these two are already handled downstream in case of lazy normalization
510 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
511 let projection_ty = relation.relate(a_data, b_data)?;
512 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
515 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
516 if a_def_id == b_def_id =>
518 let substs = relate_substs(relation, None, a_substs, b_substs)?;
519 Ok(tcx.mk_opaque(a_def_id, substs))
522 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
526 /// The main "const relation" routine. Note that this does not handle
527 /// inference artifacts, so you should filter those out before calling
529 pub fn super_relate_consts<R: TypeRelation<'tcx>>(
531 a: &'tcx ty::Const<'tcx>,
532 b: &'tcx ty::Const<'tcx>,
533 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
534 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
535 let tcx = relation.tcx();
537 // FIXME(oli-obk): once const generics can have generic types, this assertion
538 // will likely get triggered. Move to `normalize_erasing_regions` at that point.
539 let a_ty = tcx.erase_regions(a.ty);
540 let b_ty = tcx.erase_regions(b.ty);
542 relation.tcx().sess.delay_span_bug(
544 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
548 let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env());
549 let a = eagerly_eval(a);
550 let b = eagerly_eval(b);
552 // Currently, the values that can be unified are primitive types,
553 // and those that derive both `PartialEq` and `Eq`, corresponding
554 // to structural-match types.
555 let is_match = match (a.val, b.val) {
556 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
557 // The caller should handle these cases!
558 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
561 (ty::ConstKind::Error(_), _) => return Ok(a),
562 (_, ty::ConstKind::Error(_)) => return Ok(b),
564 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
565 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
566 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
567 check_const_value_eq(relation, a_val, b_val, a, b)?
570 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
571 if tcx.features().generic_const_exprs =>
573 tcx.try_unify_abstract_consts((au.shrink(), bu.shrink()))
576 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
577 // and is the better alternative to waiting until `generic_const_exprs` can
579 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
580 if au.def == bu.def && au.promoted == bu.promoted =>
582 let substs = relation.relate_with_variance(
583 ty::Variance::Invariant,
584 ty::VarianceDiagInfo::default(),
588 return Ok(tcx.mk_const(ty::Const {
589 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
591 substs_: Some(substs),
592 promoted: au.promoted,
599 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
602 fn check_const_value_eq<R: TypeRelation<'tcx>>(
604 a_val: ConstValue<'tcx>,
605 b_val: ConstValue<'tcx>,
606 // FIXME(oli-obk): these arguments should go away with valtrees
607 a: &'tcx ty::Const<'tcx>,
608 b: &'tcx ty::Const<'tcx>,
609 // FIXME(oli-obk): this should just be `bool` with valtrees
610 ) -> RelateResult<'tcx, bool> {
611 let tcx = relation.tcx();
612 Ok(match (a_val, b_val) {
613 (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
617 ConstValue::Scalar(Scalar::Ptr(a_val, _a_size)),
618 ConstValue::Scalar(Scalar::Ptr(b_val, _b_size)),
621 || match (tcx.global_alloc(a_val.provenance), tcx.global_alloc(b_val.provenance)) {
622 (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
623 a_instance == b_instance
629 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
630 get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
633 (ConstValue::ByRef { alloc: alloc_a, .. }, ConstValue::ByRef { alloc: alloc_b, .. })
634 if a.ty.is_ref() || b.ty.is_ref() =>
636 if a.ty.is_ref() && b.ty.is_ref() {
642 (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
643 let a_destructured = tcx.destructure_const(relation.param_env().and(a));
644 let b_destructured = tcx.destructure_const(relation.param_env().and(b));
646 // Both the variant and each field have to be equal.
647 if a_destructured.variant == b_destructured.variant {
648 for (a_field, b_field) in iter::zip(a_destructured.fields, b_destructured.fields) {
649 relation.consts(a_field, b_field)?;
662 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> {
663 fn relate<R: TypeRelation<'tcx>>(
667 ) -> RelateResult<'tcx, Self> {
668 let tcx = relation.tcx();
670 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
671 // We need to perform this deduplication as we sometimes generate duplicate projections
673 let mut a_v: Vec<_> = a.into_iter().collect();
674 let mut b_v: Vec<_> = b.into_iter().collect();
675 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
676 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
678 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
680 if a_v.len() != b_v.len() {
681 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
684 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
685 use crate::ty::ExistentialPredicate::*;
686 match (ep_a.skip_binder(), ep_b.skip_binder()) {
687 (Trait(a), Trait(b)) => Ok(ep_a
688 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
689 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
690 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
692 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
693 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
696 tcx.mk_poly_existential_predicates(v)
700 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
701 fn relate<R: TypeRelation<'tcx>>(
703 a: ty::ClosureSubsts<'tcx>,
704 b: ty::ClosureSubsts<'tcx>,
705 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
706 let substs = relate_substs(relation, None, a.substs, b.substs)?;
707 Ok(ty::ClosureSubsts { substs })
711 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
712 fn relate<R: TypeRelation<'tcx>>(
714 a: ty::GeneratorSubsts<'tcx>,
715 b: ty::GeneratorSubsts<'tcx>,
716 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
717 let substs = relate_substs(relation, None, a.substs, b.substs)?;
718 Ok(ty::GeneratorSubsts { substs })
722 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
723 fn relate<R: TypeRelation<'tcx>>(
727 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
728 relate_substs(relation, None, a, b)
732 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
733 fn relate<R: TypeRelation<'tcx>>(
737 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
738 relation.regions(a, b)
742 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
743 fn relate<R: TypeRelation<'tcx>>(
745 a: &'tcx ty::Const<'tcx>,
746 b: &'tcx ty::Const<'tcx>,
747 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
748 relation.consts(a, b)
752 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
753 fn relate<R: TypeRelation<'tcx>>(
755 a: ty::Binder<'tcx, T>,
756 b: ty::Binder<'tcx, T>,
757 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
758 relation.binders(a, b)
762 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
763 fn relate<R: TypeRelation<'tcx>>(
767 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
768 match (a.unpack(), b.unpack()) {
769 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
770 Ok(relation.relate(a_lt, b_lt)?.into())
772 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
773 Ok(relation.relate(a_ty, b_ty)?.into())
775 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
776 Ok(relation.relate(a_ct, b_ct)?.into())
778 (GenericArgKind::Lifetime(unpacked), x) => {
779 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
781 (GenericArgKind::Type(unpacked), x) => {
782 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
784 (GenericArgKind::Const(unpacked), x) => {
785 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
791 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
792 fn relate<R: TypeRelation<'tcx>>(
796 ) -> RelateResult<'tcx, ty::ImplPolarity> {
798 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
805 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
806 fn relate<R: TypeRelation<'tcx>>(
808 a: ty::TraitPredicate<'tcx>,
809 b: ty::TraitPredicate<'tcx>,
810 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
811 Ok(ty::TraitPredicate {
812 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
813 constness: relation.relate(a.constness, b.constness)?,
814 polarity: relation.relate(a.polarity, b.polarity)?,
819 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
820 fn relate<R: TypeRelation<'tcx>>(
822 a: ty::ProjectionPredicate<'tcx>,
823 b: ty::ProjectionPredicate<'tcx>,
824 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
825 Ok(ty::ProjectionPredicate {
826 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
827 ty: relation.relate(a.ty, b.ty)?,
832 ///////////////////////////////////////////////////////////////////////////
835 pub fn expected_found<R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
837 R: TypeRelation<'tcx>,
839 ExpectedFound::new(relation.a_is_expected(), a, b)