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)) => Err(TypeError::ArgumentSorts(exp_found, i)),
191 Err(TypeError::Mutability) => Err(TypeError::ArgumentMutability(i)),
195 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
196 c_variadic: a.c_variadic,
203 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
204 fn relate<R: TypeRelation<'tcx>>(
206 a: ty::BoundConstness,
207 b: ty::BoundConstness,
208 ) -> RelateResult<'tcx, ty::BoundConstness> {
210 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
217 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::ConstnessAnd<T> {
218 fn relate<R: TypeRelation<'tcx>>(
220 a: ty::ConstnessAnd<T>,
221 b: ty::ConstnessAnd<T>,
222 ) -> RelateResult<'tcx, ty::ConstnessAnd<T>> {
223 Ok(ty::ConstnessAnd {
224 constness: relation.relate(a.constness, b.constness)?,
225 value: relation.relate(a.value, b.value)?,
230 impl<'tcx> Relate<'tcx> for ast::Unsafety {
231 fn relate<R: TypeRelation<'tcx>>(
235 ) -> RelateResult<'tcx, ast::Unsafety> {
237 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
244 impl<'tcx> Relate<'tcx> for abi::Abi {
245 fn relate<R: TypeRelation<'tcx>>(
249 ) -> RelateResult<'tcx, abi::Abi> {
250 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
254 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
255 fn relate<R: TypeRelation<'tcx>>(
257 a: ty::ProjectionTy<'tcx>,
258 b: ty::ProjectionTy<'tcx>,
259 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
260 if a.item_def_id != b.item_def_id {
261 Err(TypeError::ProjectionMismatched(expected_found(
267 let substs = relation.relate(a.substs, b.substs)?;
268 Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
273 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
274 fn relate<R: TypeRelation<'tcx>>(
276 a: ty::ExistentialProjection<'tcx>,
277 b: ty::ExistentialProjection<'tcx>,
278 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
279 if a.item_def_id != b.item_def_id {
280 Err(TypeError::ProjectionMismatched(expected_found(
286 let ty = relation.relate_with_variance(
288 ty::VarianceDiagInfo::default(),
292 let substs = relation.relate_with_variance(
294 ty::VarianceDiagInfo::default(),
298 Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, ty })
303 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
304 fn relate<R: TypeRelation<'tcx>>(
306 a: ty::TraitRef<'tcx>,
307 b: ty::TraitRef<'tcx>,
308 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
309 // Different traits cannot be related.
310 if a.def_id != b.def_id {
311 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
313 let substs = relate_substs(relation, None, a.substs, b.substs)?;
314 Ok(ty::TraitRef { def_id: a.def_id, substs })
319 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
320 fn relate<R: TypeRelation<'tcx>>(
322 a: ty::ExistentialTraitRef<'tcx>,
323 b: ty::ExistentialTraitRef<'tcx>,
324 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
325 // Different traits cannot be related.
326 if a.def_id != b.def_id {
327 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
329 let substs = relate_substs(relation, None, a.substs, b.substs)?;
330 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
335 #[derive(Copy, Debug, Clone, TypeFoldable)]
336 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
338 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
339 fn relate<R: TypeRelation<'tcx>>(
341 a: GeneratorWitness<'tcx>,
342 b: GeneratorWitness<'tcx>,
343 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
344 assert_eq!(a.0.len(), b.0.len());
345 let tcx = relation.tcx();
346 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
347 Ok(GeneratorWitness(types))
351 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
353 fn relate<R: TypeRelation<'tcx>>(
357 ) -> RelateResult<'tcx, Ty<'tcx>> {
362 /// The main "type relation" routine. Note that this does not handle
363 /// inference artifacts, so you should filter those out before calling
365 pub fn super_relate_tys<R: TypeRelation<'tcx>>(
369 ) -> RelateResult<'tcx, Ty<'tcx>> {
370 let tcx = relation.tcx();
371 debug!("super_relate_tys: a={:?} b={:?}", a, b);
372 match (a.kind(), b.kind()) {
373 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
374 // The caller should handle these cases!
375 bug!("var types encountered in super_relate_tys")
378 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
379 bug!("bound types encountered in super_relate_tys")
382 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
396 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
398 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
400 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
401 let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
402 Ok(tcx.mk_adt(a_def, substs))
405 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
407 (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
408 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
409 relation.relate_with_variance(
411 ty::VarianceDiagInfo::default(),
416 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
419 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
422 // All Generator types with the same id represent
423 // the (anonymous) type of the same generator expression. So
424 // all of their regions should be equated.
425 let substs = relation.relate(a_substs, b_substs)?;
426 Ok(tcx.mk_generator(a_id, substs, movability))
429 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
430 // Wrap our types with a temporary GeneratorWitness struct
431 // inside the binder so we can related them
432 let a_types = a_types.map_bound(GeneratorWitness);
433 let b_types = b_types.map_bound(GeneratorWitness);
434 // Then remove the GeneratorWitness for the result
435 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
436 Ok(tcx.mk_generator_witness(types))
439 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
440 // All Closure types with the same id represent
441 // the (anonymous) type of the same closure expression. So
442 // all of their regions should be equated.
443 let substs = relation.relate(a_substs, b_substs)?;
444 Ok(tcx.mk_closure(a_id, &substs))
447 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
448 let mt = relate_type_and_mut(relation, a_mt, b_mt, ty::VarianceDiagMutKind::RawPtr)?;
452 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
453 let r = relation.relate_with_variance(
455 ty::VarianceDiagInfo::default(),
459 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
460 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
461 let mt = relate_type_and_mut(relation, a_mt, b_mt, ty::VarianceDiagMutKind::Ref)?;
462 Ok(tcx.mk_ref(r, mt))
465 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
466 let t = relation.relate(a_t, b_t)?;
467 match relation.relate(sz_a, sz_b) {
468 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
470 // Check whether the lengths are both concrete/known values,
471 // but are unequal, for better diagnostics.
473 // It might seem dubious to eagerly evaluate these constants here,
474 // we however cannot end up with errors in `Relate` during both
475 // `type_of` and `predicates_of`. This means that evaluating the
476 // constants should not cause cycle errors here.
477 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
478 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
480 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
481 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
489 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
490 let t = relation.relate(a_t, b_t)?;
494 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
495 if as_.len() == bs.len() {
497 iter::zip(as_, bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())),
499 } else if !(as_.is_empty() || bs.is_empty()) {
500 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
502 Err(TypeError::Sorts(expected_found(relation, a, b)))
506 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
507 if a_def_id == b_def_id =>
509 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
510 Ok(tcx.mk_fn_def(a_def_id, substs))
513 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
514 let fty = relation.relate(a_fty, b_fty)?;
515 Ok(tcx.mk_fn_ptr(fty))
518 // these two are already handled downstream in case of lazy normalization
519 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
520 let projection_ty = relation.relate(a_data, b_data)?;
521 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
524 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
525 if a_def_id == b_def_id =>
527 let substs = relate_substs(relation, None, a_substs, b_substs)?;
528 Ok(tcx.mk_opaque(a_def_id, substs))
531 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
535 /// The main "const relation" routine. Note that this does not handle
536 /// inference artifacts, so you should filter those out before calling
538 pub fn super_relate_consts<R: TypeRelation<'tcx>>(
540 a: &'tcx ty::Const<'tcx>,
541 b: &'tcx ty::Const<'tcx>,
542 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
543 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
544 let tcx = relation.tcx();
546 // FIXME(oli-obk): once const generics can have generic types, this assertion
547 // will likely get triggered. Move to `normalize_erasing_regions` at that point.
548 let a_ty = tcx.erase_regions(a.ty);
549 let b_ty = tcx.erase_regions(b.ty);
551 relation.tcx().sess.delay_span_bug(
553 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
557 let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env());
558 let a = eagerly_eval(a);
559 let b = eagerly_eval(b);
561 // Currently, the values that can be unified are primitive types,
562 // and those that derive both `PartialEq` and `Eq`, corresponding
563 // to structural-match types.
564 let is_match = match (a.val, b.val) {
565 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
566 // The caller should handle these cases!
567 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
570 (ty::ConstKind::Error(_), _) => return Ok(a),
571 (_, ty::ConstKind::Error(_)) => return Ok(b),
573 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
574 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
575 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
576 check_const_value_eq(relation, a_val, b_val, a, b)?
579 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
580 if tcx.features().generic_const_exprs =>
582 tcx.try_unify_abstract_consts((au.shrink(), bu.shrink()))
585 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
586 // and is the better alternative to waiting until `generic_const_exprs` can
588 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
589 if au.def == bu.def && au.promoted == bu.promoted =>
591 let substs = relation.relate_with_variance(
592 ty::Variance::Invariant,
593 ty::VarianceDiagInfo::default(),
597 return Ok(tcx.mk_const(ty::Const {
598 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
600 substs_: Some(substs),
601 promoted: au.promoted,
608 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
611 fn check_const_value_eq<R: TypeRelation<'tcx>>(
613 a_val: ConstValue<'tcx>,
614 b_val: ConstValue<'tcx>,
615 // FIXME(oli-obk): these arguments should go away with valtrees
616 a: &'tcx ty::Const<'tcx>,
617 b: &'tcx ty::Const<'tcx>,
618 // FIXME(oli-obk): this should just be `bool` with valtrees
619 ) -> RelateResult<'tcx, bool> {
620 let tcx = relation.tcx();
621 Ok(match (a_val, b_val) {
622 (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
626 ConstValue::Scalar(Scalar::Ptr(a_val, _a_size)),
627 ConstValue::Scalar(Scalar::Ptr(b_val, _b_size)),
630 || match (tcx.global_alloc(a_val.provenance), tcx.global_alloc(b_val.provenance)) {
631 (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
632 a_instance == b_instance
638 (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
639 get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
642 (ConstValue::ByRef { alloc: alloc_a, .. }, ConstValue::ByRef { alloc: alloc_b, .. })
643 if a.ty.is_ref() || b.ty.is_ref() =>
645 if a.ty.is_ref() && b.ty.is_ref() {
651 (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
652 let a_destructured = tcx.destructure_const(relation.param_env().and(a));
653 let b_destructured = tcx.destructure_const(relation.param_env().and(b));
655 // Both the variant and each field have to be equal.
656 if a_destructured.variant == b_destructured.variant {
657 for (a_field, b_field) in iter::zip(a_destructured.fields, b_destructured.fields) {
658 relation.consts(a_field, b_field)?;
671 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>> {
672 fn relate<R: TypeRelation<'tcx>>(
676 ) -> RelateResult<'tcx, Self> {
677 let tcx = relation.tcx();
679 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
680 // We need to perform this deduplication as we sometimes generate duplicate projections
682 let mut a_v: Vec<_> = a.into_iter().collect();
683 let mut b_v: Vec<_> = b.into_iter().collect();
684 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
685 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
687 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
689 if a_v.len() != b_v.len() {
690 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
693 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
694 use crate::ty::ExistentialPredicate::*;
695 match (ep_a.skip_binder(), ep_b.skip_binder()) {
696 (Trait(a), Trait(b)) => Ok(ep_a
697 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
698 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
699 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
701 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
702 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
705 tcx.mk_poly_existential_predicates(v)
709 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
710 fn relate<R: TypeRelation<'tcx>>(
712 a: ty::ClosureSubsts<'tcx>,
713 b: ty::ClosureSubsts<'tcx>,
714 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
715 let substs = relate_substs(relation, None, a.substs, b.substs)?;
716 Ok(ty::ClosureSubsts { substs })
720 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
721 fn relate<R: TypeRelation<'tcx>>(
723 a: ty::GeneratorSubsts<'tcx>,
724 b: ty::GeneratorSubsts<'tcx>,
725 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
726 let substs = relate_substs(relation, None, a.substs, b.substs)?;
727 Ok(ty::GeneratorSubsts { substs })
731 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
732 fn relate<R: TypeRelation<'tcx>>(
736 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
737 relate_substs(relation, None, a, b)
741 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
742 fn relate<R: TypeRelation<'tcx>>(
746 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
747 relation.regions(a, b)
751 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
752 fn relate<R: TypeRelation<'tcx>>(
754 a: &'tcx ty::Const<'tcx>,
755 b: &'tcx ty::Const<'tcx>,
756 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
757 relation.consts(a, b)
761 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
762 fn relate<R: TypeRelation<'tcx>>(
764 a: ty::Binder<'tcx, T>,
765 b: ty::Binder<'tcx, T>,
766 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
767 relation.binders(a, b)
771 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
772 fn relate<R: TypeRelation<'tcx>>(
776 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
777 match (a.unpack(), b.unpack()) {
778 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
779 Ok(relation.relate(a_lt, b_lt)?.into())
781 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
782 Ok(relation.relate(a_ty, b_ty)?.into())
784 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
785 Ok(relation.relate(a_ct, b_ct)?.into())
787 (GenericArgKind::Lifetime(unpacked), x) => {
788 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
790 (GenericArgKind::Type(unpacked), x) => {
791 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
793 (GenericArgKind::Const(unpacked), x) => {
794 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
800 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
801 fn relate<R: TypeRelation<'tcx>>(
803 a: ty::TraitPredicate<'tcx>,
804 b: ty::TraitPredicate<'tcx>,
805 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
806 Ok(ty::TraitPredicate {
807 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
808 constness: relation.relate(a.constness, b.constness)?,
813 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
814 fn relate<R: TypeRelation<'tcx>>(
816 a: ty::ProjectionPredicate<'tcx>,
817 b: ty::ProjectionPredicate<'tcx>,
818 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
819 Ok(ty::ProjectionPredicate {
820 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
821 ty: relation.relate(a.ty, b.ty)?,
826 ///////////////////////////////////////////////////////////////////////////
829 pub fn expected_found<R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
831 R: TypeRelation<'tcx>,
833 expected_found_bool(relation.a_is_expected(), a, b)
836 pub fn expected_found_bool<T>(a_is_expected: bool, a: T, b: T) -> ExpectedFound<T> {
838 ExpectedFound { expected: a, found: b }
840 ExpectedFound { expected: b, found: a }