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::ty::error::{ExpectedFound, TypeError};
8 use crate::ty::{self, ImplSubject, Term, TermKind, Ty, TyCtxt, TypeFoldable};
9 use crate::ty::{GenericArg, GenericArgKind, SubstsRef};
11 use rustc_hir::def_id::DefId;
12 use rustc_span::DUMMY_SP;
13 use rustc_target::spec::abi;
16 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
18 #[derive(Clone, Debug)]
20 ExistentialRegionBound, // relating an existential region bound
23 pub trait TypeRelation<'tcx>: Sized {
24 fn tcx(&self) -> TyCtxt<'tcx>;
26 fn param_env(&self) -> ty::ParamEnv<'tcx>;
28 /// Returns a static string we can use for printouts.
29 fn tag(&self) -> &'static str;
31 /// Returns `true` if the value `a` is the "expected" type in the
32 /// relation. Just affects error messages.
33 fn a_is_expected(&self) -> bool;
35 fn with_cause<F, R>(&mut self, _cause: Cause, f: F) -> R
37 F: FnOnce(&mut Self) -> R,
42 /// Generic relation routine suitable for most anything.
43 fn relate<T: Relate<'tcx>>(&mut self, a: T, b: T) -> RelateResult<'tcx, T> {
44 Relate::relate(self, a, b)
47 /// Relate the two substitutions for the given item. The default
48 /// is to look up the variance for the item and proceed
50 fn relate_item_substs(
53 a_subst: SubstsRef<'tcx>,
54 b_subst: SubstsRef<'tcx>,
55 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
57 "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
58 item_def_id, a_subst, b_subst
62 let opt_variances = tcx.variances_of(item_def_id);
63 relate_substs_with_variances(self, item_def_id, opt_variances, a_subst, b_subst, true)
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>>;
93 ) -> RelateResult<'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>,
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 => {
129 (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 })
132 let ty = relation.relate_with_variance(variance, info, a.ty, b.ty)?;
133 Ok(ty::TypeAndMut { ty, mutbl })
138 pub fn relate_substs<'tcx, R: TypeRelation<'tcx>>(
140 a_subst: SubstsRef<'tcx>,
141 b_subst: SubstsRef<'tcx>,
142 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
143 relation.tcx().mk_substs(iter::zip(a_subst, b_subst).map(|(a, b)| {
144 relation.relate_with_variance(ty::Invariant, ty::VarianceDiagInfo::default(), a, b)
148 pub fn relate_substs_with_variances<'tcx, R: TypeRelation<'tcx>>(
151 variances: &[ty::Variance],
152 a_subst: SubstsRef<'tcx>,
153 b_subst: SubstsRef<'tcx>,
154 fetch_ty_for_diag: bool,
155 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
156 let tcx = relation.tcx();
158 let mut cached_ty = None;
159 let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| {
160 let variance = variances[i];
161 let variance_info = if variance == ty::Invariant && fetch_ty_for_diag {
163 *cached_ty.get_or_insert_with(|| tcx.bound_type_of(ty_def_id).subst(tcx, a_subst));
164 ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() }
166 ty::VarianceDiagInfo::default()
168 relation.relate_with_variance(variance, variance_info, a, b)
171 tcx.mk_substs(params)
174 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
175 fn relate<R: TypeRelation<'tcx>>(
179 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
180 let tcx = relation.tcx();
182 if a.c_variadic != b.c_variadic {
183 return Err(TypeError::VariadicMismatch(expected_found(
189 let unsafety = relation.relate(a.unsafety, b.unsafety)?;
190 let abi = relation.relate(a.abi, b.abi)?;
192 if a.inputs().len() != b.inputs().len() {
193 return Err(TypeError::ArgCount);
196 let inputs_and_output = iter::zip(a.inputs(), b.inputs())
197 .map(|(&a, &b)| ((a, b), false))
198 .chain(iter::once(((a.output(), b.output()), true)))
199 .map(|((a, b), is_output)| {
201 relation.relate(a, b)
203 relation.relate_with_variance(
205 ty::VarianceDiagInfo::default(),
212 .map(|(i, r)| match r {
213 Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
214 Err(TypeError::ArgumentSorts(exp_found, i))
216 Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
217 Err(TypeError::ArgumentMutability(i))
222 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
223 c_variadic: a.c_variadic,
230 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
231 fn relate<R: TypeRelation<'tcx>>(
233 a: ty::BoundConstness,
234 b: ty::BoundConstness,
235 ) -> RelateResult<'tcx, ty::BoundConstness> {
237 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
244 impl<'tcx> Relate<'tcx> for ast::Unsafety {
245 fn relate<R: TypeRelation<'tcx>>(
249 ) -> RelateResult<'tcx, ast::Unsafety> {
251 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
258 impl<'tcx> Relate<'tcx> for abi::Abi {
259 fn relate<R: TypeRelation<'tcx>>(
263 ) -> RelateResult<'tcx, abi::Abi> {
264 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
268 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
269 fn relate<R: TypeRelation<'tcx>>(
271 a: ty::ProjectionTy<'tcx>,
272 b: ty::ProjectionTy<'tcx>,
273 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
274 if a.item_def_id != b.item_def_id {
275 Err(TypeError::ProjectionMismatched(expected_found(
281 let substs = relation.relate(a.substs, b.substs)?;
282 Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
287 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
288 fn relate<R: TypeRelation<'tcx>>(
290 a: ty::ExistentialProjection<'tcx>,
291 b: ty::ExistentialProjection<'tcx>,
292 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
293 if a.item_def_id != b.item_def_id {
294 Err(TypeError::ProjectionMismatched(expected_found(
300 let term = relation.relate_with_variance(
302 ty::VarianceDiagInfo::default(),
306 let substs = relation.relate_with_variance(
308 ty::VarianceDiagInfo::default(),
312 Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, term })
317 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
318 fn relate<R: TypeRelation<'tcx>>(
320 a: ty::TraitRef<'tcx>,
321 b: ty::TraitRef<'tcx>,
322 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
323 // Different traits cannot be related.
324 if a.def_id != b.def_id {
325 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
327 let substs = relate_substs(relation, a.substs, b.substs)?;
328 Ok(ty::TraitRef { def_id: a.def_id, substs })
333 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
334 fn relate<R: TypeRelation<'tcx>>(
336 a: ty::ExistentialTraitRef<'tcx>,
337 b: ty::ExistentialTraitRef<'tcx>,
338 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
339 // Different traits cannot be related.
340 if a.def_id != b.def_id {
341 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
343 let substs = relate_substs(relation, a.substs, b.substs)?;
344 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
349 #[derive(Copy, Debug, Clone, TypeFoldable, TypeVisitable)]
350 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
352 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
353 fn relate<R: TypeRelation<'tcx>>(
355 a: GeneratorWitness<'tcx>,
356 b: GeneratorWitness<'tcx>,
357 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
358 assert_eq!(a.0.len(), b.0.len());
359 let tcx = relation.tcx();
360 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
361 Ok(GeneratorWitness(types))
365 impl<'tcx> Relate<'tcx> for ImplSubject<'tcx> {
367 fn relate<R: TypeRelation<'tcx>>(
369 a: ImplSubject<'tcx>,
370 b: ImplSubject<'tcx>,
371 ) -> RelateResult<'tcx, ImplSubject<'tcx>> {
373 (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
374 let trait_ref = ty::TraitRef::relate(relation, trait_ref_a, trait_ref_b)?;
375 Ok(ImplSubject::Trait(trait_ref))
377 (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
378 let ty = Ty::relate(relation, ty_a, ty_b)?;
379 Ok(ImplSubject::Inherent(ty))
381 (ImplSubject::Trait(_), ImplSubject::Inherent(_))
382 | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
383 bug!("can not relate TraitRef and Ty");
389 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
391 fn relate<R: TypeRelation<'tcx>>(
395 ) -> RelateResult<'tcx, Ty<'tcx>> {
400 /// The main "type relation" routine. Note that this does not handle
401 /// inference artifacts, so you should filter those out before calling
403 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
407 ) -> RelateResult<'tcx, Ty<'tcx>> {
408 let tcx = relation.tcx();
409 debug!("super_relate_tys: a={:?} b={:?}", a, b);
410 match (a.kind(), b.kind()) {
411 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
412 // The caller should handle these cases!
413 bug!("var types encountered in super_relate_tys")
416 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
417 bug!("bound types encountered in super_relate_tys")
420 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
434 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
436 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
438 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
439 let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
440 Ok(tcx.mk_adt(a_def, substs))
443 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
445 (&ty::Dynamic(a_obj, a_region, a_repr), &ty::Dynamic(b_obj, b_region, b_repr))
446 if a_repr == b_repr =>
448 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
449 relation.relate_with_variance(
451 ty::VarianceDiagInfo::default(),
456 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr))
459 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
462 // All Generator types with the same id represent
463 // the (anonymous) type of the same generator expression. So
464 // all of their regions should be equated.
465 let substs = relation.relate(a_substs, b_substs)?;
466 Ok(tcx.mk_generator(a_id, substs, movability))
469 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
470 // Wrap our types with a temporary GeneratorWitness struct
471 // inside the binder so we can related them
472 let a_types = a_types.map_bound(GeneratorWitness);
473 let b_types = b_types.map_bound(GeneratorWitness);
474 // Then remove the GeneratorWitness for the result
475 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
476 Ok(tcx.mk_generator_witness(types))
479 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
480 // All Closure types with the same id represent
481 // the (anonymous) type of the same closure expression. So
482 // all of their regions should be equated.
483 let substs = relation.relate(a_substs, b_substs)?;
484 Ok(tcx.mk_closure(a_id, &substs))
487 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
488 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
492 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
493 let r = relation.relate_with_variance(
495 ty::VarianceDiagInfo::default(),
499 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
500 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
501 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
502 Ok(tcx.mk_ref(r, mt))
505 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
506 let t = relation.relate(a_t, b_t)?;
507 match relation.relate(sz_a, sz_b) {
508 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
510 // Check whether the lengths are both concrete/known values,
511 // but are unequal, for better diagnostics.
513 // It might seem dubious to eagerly evaluate these constants here,
514 // we however cannot end up with errors in `Relate` during both
515 // `type_of` and `predicates_of`. This means that evaluating the
516 // constants should not cause cycle errors here.
517 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
518 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
520 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
521 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
529 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
530 let t = relation.relate(a_t, b_t)?;
534 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
535 if as_.len() == bs.len() {
536 Ok(tcx.mk_tup(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
537 } else if !(as_.is_empty() || bs.is_empty()) {
538 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
540 Err(TypeError::Sorts(expected_found(relation, a, b)))
544 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
545 if a_def_id == b_def_id =>
547 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
548 Ok(tcx.mk_fn_def(a_def_id, substs))
551 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
552 let fty = relation.relate(a_fty, b_fty)?;
553 Ok(tcx.mk_fn_ptr(fty))
556 // these two are already handled downstream in case of lazy normalization
557 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
558 let projection_ty = relation.relate(a_data, b_data)?;
559 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
562 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
563 if a_def_id == b_def_id =>
565 let opt_variances = tcx.variances_of(a_def_id);
566 let substs = relate_substs_with_variances(
572 false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
574 Ok(tcx.mk_opaque(a_def_id, substs))
577 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
581 /// The main "const relation" routine. Note that this does not handle
582 /// inference artifacts, so you should filter those out before calling
584 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
586 mut a: ty::Const<'tcx>,
587 mut b: ty::Const<'tcx>,
588 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
589 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
590 let tcx = relation.tcx();
594 if relation.tcx().features().adt_const_params {
595 a_ty = tcx.normalize_erasing_regions(relation.param_env(), a.ty());
596 b_ty = tcx.normalize_erasing_regions(relation.param_env(), b.ty());
598 a_ty = tcx.erase_regions(a.ty());
599 b_ty = tcx.erase_regions(b.ty());
602 relation.tcx().sess.delay_span_bug(
604 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
608 // HACK(const_generics): We still need to eagerly evaluate consts when
609 // relating them because during `normalize_param_env_or_error`,
610 // we may relate an evaluated constant in a obligation against
611 // an unnormalized (i.e. unevaluated) const in the param-env.
612 // FIXME(generic_const_exprs): Once we always lazily unify unevaluated constants
613 // these `eval` calls can be removed.
614 if !relation.tcx().features().generic_const_exprs {
615 a = a.eval(tcx, relation.param_env());
616 b = b.eval(tcx, relation.param_env());
619 // Currently, the values that can be unified are primitive types,
620 // and those that derive both `PartialEq` and `Eq`, corresponding
621 // to structural-match types.
622 let is_match = match (a.kind(), b.kind()) {
623 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
624 // The caller should handle these cases!
625 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
628 (ty::ConstKind::Error(_), _) => return Ok(a),
629 (_, ty::ConstKind::Error(_)) => return Ok(b),
631 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
632 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
633 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
635 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
636 if tcx.features().generic_const_exprs =>
638 tcx.try_unify_abstract_consts(relation.param_env().and((au, bu)))
641 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
642 // and is the better alternative to waiting until `generic_const_exprs` can
644 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
645 let substs = relation.relate_with_variance(
646 ty::Variance::Invariant,
647 ty::VarianceDiagInfo::default(),
651 return Ok(tcx.mk_const(
652 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def: au.def, substs }),
658 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
661 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
662 fn relate<R: TypeRelation<'tcx>>(
666 ) -> RelateResult<'tcx, Self> {
667 let tcx = relation.tcx();
669 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
670 // We need to perform this deduplication as we sometimes generate duplicate projections
672 let mut a_v: Vec<_> = a.into_iter().collect();
673 let mut b_v: Vec<_> = b.into_iter().collect();
674 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
675 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
677 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
679 if a_v.len() != b_v.len() {
680 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
683 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
684 use crate::ty::ExistentialPredicate::*;
685 match (ep_a.skip_binder(), ep_b.skip_binder()) {
686 (Trait(a), Trait(b)) => Ok(ep_a
687 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
688 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
689 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
691 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
692 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
695 tcx.mk_poly_existential_predicates(v)
699 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
700 fn relate<R: TypeRelation<'tcx>>(
702 a: ty::ClosureSubsts<'tcx>,
703 b: ty::ClosureSubsts<'tcx>,
704 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
705 let substs = relate_substs(relation, a.substs, b.substs)?;
706 Ok(ty::ClosureSubsts { substs })
710 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
711 fn relate<R: TypeRelation<'tcx>>(
713 a: ty::GeneratorSubsts<'tcx>,
714 b: ty::GeneratorSubsts<'tcx>,
715 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
716 let substs = relate_substs(relation, a.substs, b.substs)?;
717 Ok(ty::GeneratorSubsts { substs })
721 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
722 fn relate<R: TypeRelation<'tcx>>(
726 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
727 relate_substs(relation, a, b)
731 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
732 fn relate<R: TypeRelation<'tcx>>(
736 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
737 relation.regions(a, b)
741 impl<'tcx> Relate<'tcx> for ty::Const<'tcx> {
742 fn relate<R: TypeRelation<'tcx>>(
746 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
747 relation.consts(a, b)
751 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
752 fn relate<R: TypeRelation<'tcx>>(
754 a: ty::Binder<'tcx, T>,
755 b: ty::Binder<'tcx, T>,
756 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
757 relation.binders(a, b)
761 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
762 fn relate<R: TypeRelation<'tcx>>(
766 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
767 match (a.unpack(), b.unpack()) {
768 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
769 Ok(relation.relate(a_lt, b_lt)?.into())
771 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
772 Ok(relation.relate(a_ty, b_ty)?.into())
774 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
775 Ok(relation.relate(a_ct, b_ct)?.into())
777 (GenericArgKind::Lifetime(unpacked), x) => {
778 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
780 (GenericArgKind::Type(unpacked), x) => {
781 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
783 (GenericArgKind::Const(unpacked), x) => {
784 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
790 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
791 fn relate<R: TypeRelation<'tcx>>(
795 ) -> RelateResult<'tcx, ty::ImplPolarity> {
797 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
804 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
805 fn relate<R: TypeRelation<'tcx>>(
807 a: ty::TraitPredicate<'tcx>,
808 b: ty::TraitPredicate<'tcx>,
809 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
810 Ok(ty::TraitPredicate {
811 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
812 constness: relation.relate(a.constness, b.constness)?,
813 polarity: relation.relate(a.polarity, b.polarity)?,
818 impl<'tcx> Relate<'tcx> for Term<'tcx> {
819 fn relate<R: TypeRelation<'tcx>>(
823 ) -> RelateResult<'tcx, Self> {
824 Ok(match (a.unpack(), b.unpack()) {
825 (TermKind::Ty(a), TermKind::Ty(b)) => relation.relate(a, b)?.into(),
826 (TermKind::Const(a), TermKind::Const(b)) => relation.relate(a, b)?.into(),
827 _ => return Err(TypeError::Mismatch),
832 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
833 fn relate<R: TypeRelation<'tcx>>(
835 a: ty::ProjectionPredicate<'tcx>,
836 b: ty::ProjectionPredicate<'tcx>,
837 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
838 Ok(ty::ProjectionPredicate {
839 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
840 term: relation.relate(a.term, b.term)?,
845 ///////////////////////////////////////////////////////////////////////////
848 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
850 R: TypeRelation<'tcx>,
852 ExpectedFound::new(relation.a_is_expected(), a, b)