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)
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 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
155 let tcx = relation.tcx();
157 let mut cached_ty = None;
158 let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| {
159 let variance = variances[i];
160 let variance_info = if variance == ty::Invariant {
162 *cached_ty.get_or_insert_with(|| tcx.bound_type_of(ty_def_id).subst(tcx, a_subst));
163 ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() }
165 ty::VarianceDiagInfo::default()
167 relation.relate_with_variance(variance, variance_info, a, b)
170 tcx.mk_substs(params)
173 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
174 fn relate<R: TypeRelation<'tcx>>(
178 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
179 let tcx = relation.tcx();
181 if a.c_variadic != b.c_variadic {
182 return Err(TypeError::VariadicMismatch(expected_found(
188 let unsafety = relation.relate(a.unsafety, b.unsafety)?;
189 let abi = relation.relate(a.abi, b.abi)?;
191 if a.inputs().len() != b.inputs().len() {
192 return Err(TypeError::ArgCount);
195 let inputs_and_output = iter::zip(a.inputs(), b.inputs())
196 .map(|(&a, &b)| ((a, b), false))
197 .chain(iter::once(((a.output(), b.output()), true)))
198 .map(|((a, b), is_output)| {
200 relation.relate(a, b)
202 relation.relate_with_variance(
204 ty::VarianceDiagInfo::default(),
211 .map(|(i, r)| match r {
212 Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
213 Err(TypeError::ArgumentSorts(exp_found, i))
215 Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
216 Err(TypeError::ArgumentMutability(i))
221 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
222 c_variadic: a.c_variadic,
229 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
230 fn relate<R: TypeRelation<'tcx>>(
232 a: ty::BoundConstness,
233 b: ty::BoundConstness,
234 ) -> RelateResult<'tcx, ty::BoundConstness> {
236 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
243 impl<'tcx> Relate<'tcx> for ast::Unsafety {
244 fn relate<R: TypeRelation<'tcx>>(
248 ) -> RelateResult<'tcx, ast::Unsafety> {
250 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
257 impl<'tcx> Relate<'tcx> for abi::Abi {
258 fn relate<R: TypeRelation<'tcx>>(
262 ) -> RelateResult<'tcx, abi::Abi> {
263 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
267 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
268 fn relate<R: TypeRelation<'tcx>>(
270 a: ty::ProjectionTy<'tcx>,
271 b: ty::ProjectionTy<'tcx>,
272 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
273 if a.item_def_id != b.item_def_id {
274 Err(TypeError::ProjectionMismatched(expected_found(
280 let substs = relation.relate(a.substs, b.substs)?;
281 Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
286 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
287 fn relate<R: TypeRelation<'tcx>>(
289 a: ty::ExistentialProjection<'tcx>,
290 b: ty::ExistentialProjection<'tcx>,
291 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
292 if a.item_def_id != b.item_def_id {
293 Err(TypeError::ProjectionMismatched(expected_found(
299 let term = relation.relate_with_variance(
301 ty::VarianceDiagInfo::default(),
305 let substs = relation.relate_with_variance(
307 ty::VarianceDiagInfo::default(),
311 Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, term })
316 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
317 fn relate<R: TypeRelation<'tcx>>(
319 a: ty::TraitRef<'tcx>,
320 b: ty::TraitRef<'tcx>,
321 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
322 // Different traits cannot be related.
323 if a.def_id != b.def_id {
324 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
326 let substs = relate_substs(relation, a.substs, b.substs)?;
327 Ok(ty::TraitRef { def_id: a.def_id, substs })
332 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
333 fn relate<R: TypeRelation<'tcx>>(
335 a: ty::ExistentialTraitRef<'tcx>,
336 b: ty::ExistentialTraitRef<'tcx>,
337 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
338 // Different traits cannot be related.
339 if a.def_id != b.def_id {
340 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
342 let substs = relate_substs(relation, a.substs, b.substs)?;
343 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
348 #[derive(Copy, Debug, Clone, TypeFoldable, TypeVisitable)]
349 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
351 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
352 fn relate<R: TypeRelation<'tcx>>(
354 a: GeneratorWitness<'tcx>,
355 b: GeneratorWitness<'tcx>,
356 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
357 assert_eq!(a.0.len(), b.0.len());
358 let tcx = relation.tcx();
359 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
360 Ok(GeneratorWitness(types))
364 impl<'tcx> Relate<'tcx> for ImplSubject<'tcx> {
366 fn relate<R: TypeRelation<'tcx>>(
368 a: ImplSubject<'tcx>,
369 b: ImplSubject<'tcx>,
370 ) -> RelateResult<'tcx, ImplSubject<'tcx>> {
372 (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
373 let trait_ref = ty::TraitRef::relate(relation, trait_ref_a, trait_ref_b)?;
374 Ok(ImplSubject::Trait(trait_ref))
376 (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
377 let ty = Ty::relate(relation, ty_a, ty_b)?;
378 Ok(ImplSubject::Inherent(ty))
380 (ImplSubject::Trait(_), ImplSubject::Inherent(_))
381 | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
382 bug!("can not relate TraitRef and Ty");
388 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
390 fn relate<R: TypeRelation<'tcx>>(
394 ) -> RelateResult<'tcx, Ty<'tcx>> {
399 /// The main "type relation" routine. Note that this does not handle
400 /// inference artifacts, so you should filter those out before calling
402 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
406 ) -> RelateResult<'tcx, Ty<'tcx>> {
407 let tcx = relation.tcx();
408 debug!("super_relate_tys: a={:?} b={:?}", a, b);
409 match (a.kind(), b.kind()) {
410 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
411 // The caller should handle these cases!
412 bug!("var types encountered in super_relate_tys")
415 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
416 bug!("bound types encountered in super_relate_tys")
419 (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
433 (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
435 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
437 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
438 let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
439 Ok(tcx.mk_adt(a_def, substs))
442 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
444 (&ty::Dynamic(a_obj, a_region, a_repr), &ty::Dynamic(b_obj, b_region, b_repr))
445 if a_repr == b_repr =>
447 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
448 relation.relate_with_variance(
450 ty::VarianceDiagInfo::default(),
455 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr))
458 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
461 // All Generator types with the same id represent
462 // the (anonymous) type of the same generator expression. So
463 // all of their regions should be equated.
464 let substs = relation.relate(a_substs, b_substs)?;
465 Ok(tcx.mk_generator(a_id, substs, movability))
468 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
469 // Wrap our types with a temporary GeneratorWitness struct
470 // inside the binder so we can related them
471 let a_types = a_types.map_bound(GeneratorWitness);
472 let b_types = b_types.map_bound(GeneratorWitness);
473 // Then remove the GeneratorWitness for the result
474 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
475 Ok(tcx.mk_generator_witness(types))
478 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
479 // All Closure types with the same id represent
480 // the (anonymous) type of the same closure expression. So
481 // all of their regions should be equated.
482 let substs = relation.relate(a_substs, b_substs)?;
483 Ok(tcx.mk_closure(a_id, &substs))
486 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
487 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
491 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
492 let r = relation.relate_with_variance(
494 ty::VarianceDiagInfo::default(),
498 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
499 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
500 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
501 Ok(tcx.mk_ref(r, mt))
504 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
505 let t = relation.relate(a_t, b_t)?;
506 match relation.relate(sz_a, sz_b) {
507 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
509 // Check whether the lengths are both concrete/known values,
510 // but are unequal, for better diagnostics.
512 // It might seem dubious to eagerly evaluate these constants here,
513 // we however cannot end up with errors in `Relate` during both
514 // `type_of` and `predicates_of`. This means that evaluating the
515 // constants should not cause cycle errors here.
516 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
517 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
519 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
520 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
528 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
529 let t = relation.relate(a_t, b_t)?;
533 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
534 if as_.len() == bs.len() {
535 Ok(tcx.mk_tup(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
536 } else if !(as_.is_empty() || bs.is_empty()) {
537 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
539 Err(TypeError::Sorts(expected_found(relation, a, b)))
543 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
544 if a_def_id == b_def_id =>
546 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
547 Ok(tcx.mk_fn_def(a_def_id, substs))
550 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
551 let fty = relation.relate(a_fty, b_fty)?;
552 Ok(tcx.mk_fn_ptr(fty))
555 // these two are already handled downstream in case of lazy normalization
556 (&ty::Projection(a_data), &ty::Projection(b_data)) => {
557 let projection_ty = relation.relate(a_data, b_data)?;
558 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
561 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
562 if a_def_id == b_def_id =>
564 let substs = relate_substs(relation, a_substs, b_substs)?;
565 Ok(tcx.mk_opaque(a_def_id, substs))
568 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
572 /// The main "const relation" routine. Note that this does not handle
573 /// inference artifacts, so you should filter those out before calling
575 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
577 mut a: ty::Const<'tcx>,
578 mut b: ty::Const<'tcx>,
579 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
580 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
581 let tcx = relation.tcx();
585 if relation.tcx().features().adt_const_params {
586 a_ty = tcx.normalize_erasing_regions(relation.param_env(), a.ty());
587 b_ty = tcx.normalize_erasing_regions(relation.param_env(), b.ty());
589 a_ty = tcx.erase_regions(a.ty());
590 b_ty = tcx.erase_regions(b.ty());
593 relation.tcx().sess.delay_span_bug(
595 &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
599 // HACK(const_generics): We still need to eagerly evaluate consts when
600 // relating them because during `normalize_param_env_or_error`,
601 // we may relate an evaluated constant in a obligation against
602 // an unnormalized (i.e. unevaluated) const in the param-env.
603 // FIXME(generic_const_exprs): Once we always lazily unify unevaluated constants
604 // these `eval` calls can be removed.
605 if !relation.tcx().features().generic_const_exprs {
606 a = a.eval(tcx, relation.param_env());
607 b = b.eval(tcx, relation.param_env());
610 // Currently, the values that can be unified are primitive types,
611 // and those that derive both `PartialEq` and `Eq`, corresponding
612 // to structural-match types.
613 let is_match = match (a.kind(), b.kind()) {
614 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
615 // The caller should handle these cases!
616 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
619 (ty::ConstKind::Error(_), _) => return Ok(a),
620 (_, ty::ConstKind::Error(_)) => return Ok(b),
622 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
623 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
624 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
626 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
627 if tcx.features().generic_const_exprs =>
629 tcx.try_unify_abstract_consts(relation.param_env().and((au, bu)))
632 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
633 // and is the better alternative to waiting until `generic_const_exprs` can
635 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
636 let substs = relation.relate_with_variance(
637 ty::Variance::Invariant,
638 ty::VarianceDiagInfo::default(),
642 return Ok(tcx.mk_const(
643 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def: au.def, substs }),
649 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
652 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
653 fn relate<R: TypeRelation<'tcx>>(
657 ) -> RelateResult<'tcx, Self> {
658 let tcx = relation.tcx();
660 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
661 // We need to perform this deduplication as we sometimes generate duplicate projections
663 let mut a_v: Vec<_> = a.into_iter().collect();
664 let mut b_v: Vec<_> = b.into_iter().collect();
665 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
666 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
668 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
670 if a_v.len() != b_v.len() {
671 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
674 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
675 use crate::ty::ExistentialPredicate::*;
676 match (ep_a.skip_binder(), ep_b.skip_binder()) {
677 (Trait(a), Trait(b)) => Ok(ep_a
678 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
679 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
680 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
682 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
683 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
686 tcx.mk_poly_existential_predicates(v)
690 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
691 fn relate<R: TypeRelation<'tcx>>(
693 a: ty::ClosureSubsts<'tcx>,
694 b: ty::ClosureSubsts<'tcx>,
695 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
696 let substs = relate_substs(relation, a.substs, b.substs)?;
697 Ok(ty::ClosureSubsts { substs })
701 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
702 fn relate<R: TypeRelation<'tcx>>(
704 a: ty::GeneratorSubsts<'tcx>,
705 b: ty::GeneratorSubsts<'tcx>,
706 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
707 let substs = relate_substs(relation, a.substs, b.substs)?;
708 Ok(ty::GeneratorSubsts { substs })
712 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
713 fn relate<R: TypeRelation<'tcx>>(
717 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
718 relate_substs(relation, a, b)
722 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
723 fn relate<R: TypeRelation<'tcx>>(
727 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
728 relation.regions(a, b)
732 impl<'tcx> Relate<'tcx> for ty::Const<'tcx> {
733 fn relate<R: TypeRelation<'tcx>>(
737 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
738 relation.consts(a, b)
742 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
743 fn relate<R: TypeRelation<'tcx>>(
745 a: ty::Binder<'tcx, T>,
746 b: ty::Binder<'tcx, T>,
747 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
748 relation.binders(a, b)
752 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
753 fn relate<R: TypeRelation<'tcx>>(
757 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
758 match (a.unpack(), b.unpack()) {
759 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
760 Ok(relation.relate(a_lt, b_lt)?.into())
762 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
763 Ok(relation.relate(a_ty, b_ty)?.into())
765 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
766 Ok(relation.relate(a_ct, b_ct)?.into())
768 (GenericArgKind::Lifetime(unpacked), x) => {
769 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
771 (GenericArgKind::Type(unpacked), x) => {
772 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
774 (GenericArgKind::Const(unpacked), x) => {
775 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
781 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
782 fn relate<R: TypeRelation<'tcx>>(
786 ) -> RelateResult<'tcx, ty::ImplPolarity> {
788 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
795 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
796 fn relate<R: TypeRelation<'tcx>>(
798 a: ty::TraitPredicate<'tcx>,
799 b: ty::TraitPredicate<'tcx>,
800 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
801 Ok(ty::TraitPredicate {
802 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
803 constness: relation.relate(a.constness, b.constness)?,
804 polarity: relation.relate(a.polarity, b.polarity)?,
809 impl<'tcx> Relate<'tcx> for Term<'tcx> {
810 fn relate<R: TypeRelation<'tcx>>(
814 ) -> RelateResult<'tcx, Self> {
815 Ok(match (a.unpack(), b.unpack()) {
816 (TermKind::Ty(a), TermKind::Ty(b)) => relation.relate(a, b)?.into(),
817 (TermKind::Const(a), TermKind::Const(b)) => relation.relate(a, b)?.into(),
818 _ => return Err(TypeError::Mismatch),
823 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
824 fn relate<R: TypeRelation<'tcx>>(
826 a: ty::ProjectionPredicate<'tcx>,
827 b: ty::ProjectionPredicate<'tcx>,
828 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
829 Ok(ty::ProjectionPredicate {
830 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
831 term: relation.relate(a.term, b.term)?,
836 ///////////////////////////////////////////////////////////////////////////
839 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
841 R: TypeRelation<'tcx>,
843 ExpectedFound::new(relation.a_is_expected(), a, b)