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::hir::def_id::DefId;
8 use crate::ty::subst::{Kind, UnpackedKind, SubstsRef};
9 use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
10 use crate::ty::error::{ExpectedFound, TypeError};
11 use crate::mir::interpret::{ConstValue, Scalar, GlobalId};
14 use rustc_target::spec::abi;
15 use crate::hir as ast;
18 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
20 #[derive(Clone, Debug)]
22 ExistentialRegionBound, // relating an existential region bound
25 pub trait TypeRelation<'tcx>: Sized {
26 fn tcx(&self) -> TyCtxt<'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
36 where F: FnOnce(&mut Self) -> R
41 /// Generic relation routine suitable for most anything.
42 fn relate<T: Relate<'tcx>>(&mut self, a: &T, b: &T) -> RelateResult<'tcx, T> {
43 Relate::relate(self, a, b)
46 /// Relate the two substitutions for the given item. The default
47 /// is to look up the variance for the item and proceed
49 fn relate_item_substs(&mut self,
51 a_subst: SubstsRef<'tcx>,
52 b_subst: SubstsRef<'tcx>)
53 -> RelateResult<'tcx, SubstsRef<'tcx>>
55 debug!("relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
60 let opt_variances = self.tcx().variances_of(item_def_id);
61 relate_substs(self, Some(opt_variances), a_subst, b_subst)
64 /// Switch variance for the purpose of relating `a` and `b`.
65 fn relate_with_variance<T: Relate<'tcx>>(&mut self,
66 variance: ty::Variance,
69 -> RelateResult<'tcx, T>;
71 // Overrideable relations. You shouldn't typically call these
72 // directly, instead call `relate()`, which in turn calls
73 // these. This is both more uniform but also allows us to add
74 // additional hooks for other types in the future if needed
75 // without making older code, which called `relate`, obsolete.
77 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>;
83 ) -> RelateResult<'tcx, ty::Region<'tcx>>;
87 a: &'tcx ty::Const<'tcx>,
88 b: &'tcx ty::Const<'tcx>
89 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>;
91 fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
92 -> RelateResult<'tcx, ty::Binder<T>>
93 where T: Relate<'tcx>;
96 pub trait Relate<'tcx>: TypeFoldable<'tcx> {
97 fn relate<R: TypeRelation<'tcx>>(
101 ) -> RelateResult<'tcx, Self>;
104 ///////////////////////////////////////////////////////////////////////////
107 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
108 fn relate<R: TypeRelation<'tcx>>(
110 a: &ty::TypeAndMut<'tcx>,
111 b: &ty::TypeAndMut<'tcx>,
112 ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> {
113 debug!("{}.mts({:?}, {:?})",
117 if a.mutbl != b.mutbl {
118 Err(TypeError::Mutability)
121 let variance = match mutbl {
122 ast::Mutability::MutImmutable => ty::Covariant,
123 ast::Mutability::MutMutable => ty::Invariant,
125 let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
126 Ok(ty::TypeAndMut { ty, mutbl })
131 pub fn relate_substs<R: TypeRelation<'tcx>>(
133 variances: Option<&[ty::Variance]>,
134 a_subst: SubstsRef<'tcx>,
135 b_subst: SubstsRef<'tcx>,
136 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
137 let tcx = relation.tcx();
139 let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
140 let variance = variances.map_or(ty::Invariant, |v| v[i]);
141 relation.relate_with_variance(variance, a, b)
144 Ok(tcx.mk_substs(params)?)
147 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
148 fn relate<R: TypeRelation<'tcx>>(
152 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
153 let tcx = relation.tcx();
155 if a.c_variadic != b.c_variadic {
156 return Err(TypeError::VariadicMismatch(
157 expected_found(relation, &a.c_variadic, &b.c_variadic)));
159 let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
160 let abi = relation.relate(&a.abi, &b.abi)?;
162 if a.inputs().len() != b.inputs().len() {
163 return Err(TypeError::ArgCount);
166 let inputs_and_output = a.inputs().iter().cloned()
167 .zip(b.inputs().iter().cloned())
169 .chain(iter::once(((a.output(), b.output()), true)))
170 .map(|((a, b), is_output)| {
172 relation.relate(&a, &b)
174 relation.relate_with_variance(ty::Contravariant, &a, &b)
178 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
179 c_variadic: a.c_variadic,
186 impl<'tcx> Relate<'tcx> for ast::Unsafety {
187 fn relate<R: TypeRelation<'tcx>>(
191 ) -> RelateResult<'tcx, ast::Unsafety> {
193 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
200 impl<'tcx> Relate<'tcx> for abi::Abi {
201 fn relate<R: TypeRelation<'tcx>>(
205 ) -> RelateResult<'tcx, abi::Abi> {
209 Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
214 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
215 fn relate<R: TypeRelation<'tcx>>(
217 a: &ty::ProjectionTy<'tcx>,
218 b: &ty::ProjectionTy<'tcx>,
219 ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
220 if a.item_def_id != b.item_def_id {
221 Err(TypeError::ProjectionMismatched(
222 expected_found(relation, &a.item_def_id, &b.item_def_id)))
224 let substs = relation.relate(&a.substs, &b.substs)?;
225 Ok(ty::ProjectionTy {
226 item_def_id: a.item_def_id,
233 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
234 fn relate<R: TypeRelation<'tcx>>(
236 a: &ty::ExistentialProjection<'tcx>,
237 b: &ty::ExistentialProjection<'tcx>,
238 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
239 if a.item_def_id != b.item_def_id {
240 Err(TypeError::ProjectionMismatched(
241 expected_found(relation, &a.item_def_id, &b.item_def_id)))
243 let ty = relation.relate(&a.ty, &b.ty)?;
244 let substs = relation.relate(&a.substs, &b.substs)?;
245 Ok(ty::ExistentialProjection {
246 item_def_id: a.item_def_id,
254 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
255 fn relate<R: TypeRelation<'tcx>>(
257 a: &Vec<ty::PolyExistentialProjection<'tcx>>,
258 b: &Vec<ty::PolyExistentialProjection<'tcx>>,
259 ) -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>> {
260 // To be compatible, `a` and `b` must be for precisely the
261 // same set of traits and item names. We always require that
262 // projection bounds lists are sorted by trait-def-id and item-name,
263 // so we can just iterate through the lists pairwise, so long as they are the
265 if a.len() != b.len() {
266 Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
270 .map(|(a, b)| relation.relate(a, b))
276 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
277 fn relate<R: TypeRelation<'tcx>>(
279 a: &ty::TraitRef<'tcx>,
280 b: &ty::TraitRef<'tcx>,
281 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
282 // Different traits cannot be related
283 if a.def_id != b.def_id {
284 Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
286 let substs = relate_substs(relation, None, a.substs, b.substs)?;
287 Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
292 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
293 fn relate<R: TypeRelation<'tcx>>(
295 a: &ty::ExistentialTraitRef<'tcx>,
296 b: &ty::ExistentialTraitRef<'tcx>,
297 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
298 // Different traits cannot be related
299 if a.def_id != b.def_id {
300 Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
302 let substs = relate_substs(relation, None, a.substs, b.substs)?;
303 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
308 #[derive(Debug, Clone)]
309 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
311 TupleStructTypeFoldableImpl! {
312 impl<'tcx> TypeFoldable<'tcx> for GeneratorWitness<'tcx> {
317 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
318 fn relate<R: TypeRelation<'tcx>>(
320 a: &GeneratorWitness<'tcx>,
321 b: &GeneratorWitness<'tcx>,
322 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
323 assert_eq!(a.0.len(), b.0.len());
324 let tcx = relation.tcx();
325 let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
326 Ok(GeneratorWitness(types))
330 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
331 fn relate<R: TypeRelation<'tcx>>(
335 ) -> RelateResult<'tcx, Ty<'tcx>> {
340 /// The main "type relation" routine. Note that this does not handle
341 /// inference artifacts, so you should filter those out before calling
343 pub fn super_relate_tys<R: TypeRelation<'tcx>>(
347 ) -> RelateResult<'tcx, Ty<'tcx>> {
348 let tcx = relation.tcx();
349 debug!("super_relate_tys: a={:?} b={:?}", a, b);
350 match (&a.sty, &b.sty) {
352 (_, &ty::Infer(_)) =>
354 // The caller should handle these cases!
355 bug!("var types encountered in super_relate_tys")
358 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
359 bug!("bound types encountered in super_relate_tys")
362 (&ty::Error, _) | (_, &ty::Error) =>
379 (&ty::Param(ref a_p), &ty::Param(ref b_p))
380 if a_p.index == b_p.index =>
385 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => {
389 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs))
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))
399 Ok(tcx.mk_foreign(a_id))
402 (&ty::Dynamic(ref a_obj, ref a_region), &ty::Dynamic(ref b_obj, ref b_region)) => {
403 let region_bound = relation.with_cause(Cause::ExistentialRegionBound,
405 relation.relate_with_variance(
410 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
413 (&ty::Generator(a_id, a_substs, movability),
414 &ty::Generator(b_id, b_substs, _))
417 // All Generator types with the same id represent
418 // the (anonymous) type of the same generator expression. So
419 // all of their regions should be equated.
420 let substs = relation.relate(&a_substs, &b_substs)?;
421 Ok(tcx.mk_generator(a_id, substs, movability))
424 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) =>
426 // Wrap our types with a temporary GeneratorWitness struct
427 // inside the binder so we can related them
428 let a_types = a_types.map_bound(GeneratorWitness);
429 let b_types = b_types.map_bound(GeneratorWitness);
430 // Then remove the GeneratorWitness for the result
431 let types = relation.relate(&a_types, &b_types)?.map_bound(|witness| witness.0);
432 Ok(tcx.mk_generator_witness(types))
435 (&ty::Closure(a_id, a_substs),
436 &ty::Closure(b_id, b_substs))
439 // All Closure types with the same id represent
440 // the (anonymous) type of the same closure expression. So
441 // all of their regions should be equated.
442 let substs = relation.relate(&a_substs, &b_substs)?;
443 Ok(tcx.mk_closure(a_id, substs))
446 (&ty::RawPtr(ref a_mt), &ty::RawPtr(ref b_mt)) =>
448 let mt = relation.relate(a_mt, b_mt)?;
452 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) =>
454 let r = relation.relate_with_variance(ty::Contravariant, &a_r, &b_r)?;
455 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
456 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
457 let mt = relation.relate(&a_mt, &b_mt)?;
458 Ok(tcx.mk_ref(r, mt))
461 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) =>
463 let t = relation.relate(&a_t, &b_t)?;
464 match relation.relate(&sz_a, &sz_b) {
465 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
467 // Check whether the lengths are both concrete/known values,
468 // but are unequal, for better diagnostics.
469 match (sz_a.assert_usize(tcx), sz_b.assert_usize(tcx)) {
470 (Some(sz_a_val), Some(sz_b_val)) => {
471 Err(TypeError::FixedArraySize(
472 expected_found(relation, &sz_a_val, &sz_b_val)
475 _ => return Err(err),
481 (&ty::Slice(a_t), &ty::Slice(b_t)) =>
483 let t = relation.relate(&a_t, &b_t)?;
487 (&ty::Tuple(as_), &ty::Tuple(bs)) =>
489 if as_.len() == bs.len() {
490 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| {
491 relation.relate(&a.expect_ty(), &b.expect_ty())
493 } else if !(as_.is_empty() || bs.is_empty()) {
494 Err(TypeError::TupleSize(
495 expected_found(relation, &as_.len(), &bs.len())))
497 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
501 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
502 if a_def_id == b_def_id =>
504 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
505 Ok(tcx.mk_fn_def(a_def_id, substs))
508 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) =>
510 let fty = relation.relate(&a_fty, &b_fty)?;
511 Ok(tcx.mk_fn_ptr(fty))
514 (ty::UnnormalizedProjection(a_data), ty::UnnormalizedProjection(b_data)) => {
515 let projection_ty = relation.relate(a_data, b_data)?;
516 Ok(tcx.mk_ty(ty::UnnormalizedProjection(projection_ty)))
519 // these two are already handled downstream in case of lazy normalization
520 (ty::Projection(a_data), ty::Projection(b_data)) => {
521 let projection_ty = relation.relate(a_data, b_data)?;
522 Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
525 (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
526 if a_def_id == b_def_id =>
528 let substs = relate_substs(relation, None, a_substs, b_substs)?;
529 Ok(tcx.mk_opaque(a_def_id, substs))
534 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
539 /// The main "const relation" routine. Note that this does not handle
540 /// inference artifacts, so you should filter those out before calling
542 pub fn super_relate_consts<R: TypeRelation<'tcx>>(
544 a: &'tcx ty::Const<'tcx>,
545 b: &'tcx ty::Const<'tcx>,
546 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
547 let tcx = relation.tcx();
549 let eagerly_eval = |x: &'tcx ty::Const<'tcx>| {
550 if let ConstValue::Unevaluated(def_id, substs) = x.val {
551 // FIXME(eddyb) get the right param_env.
552 let param_env = ty::ParamEnv::empty();
553 if !substs.has_local_value() {
554 let instance = ty::Instance::resolve(
560 if let Some(instance) = instance {
565 if let Ok(ct) = tcx.const_eval(param_env.and(cid)) {
574 // Currently, the values that can be unified are those that
575 // implement both `PartialEq` and `Eq`, corresponding to
576 // `structural_match` types.
577 // FIXME(const_generics): check for `structural_match` synthetic attribute.
578 match (eagerly_eval(a), eagerly_eval(b)) {
579 (ConstValue::Infer(_), _) | (_, ConstValue::Infer(_)) => {
580 // The caller should handle these cases!
581 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
583 (ConstValue::Param(a_p), ConstValue::Param(b_p)) if a_p.index == b_p.index => {
586 (ConstValue::Placeholder(p1), ConstValue::Placeholder(p2)) if p1 == p2 => {
589 (a_val @ ConstValue::Scalar(Scalar::Raw { .. }), b_val @ _)
590 if a.ty == b.ty && a_val == b_val =>
592 Ok(tcx.mk_const(ty::Const {
598 // FIXME(const_generics): we should either handle `Scalar::Ptr` or add a comment
599 // saying that we're not handling it intentionally.
601 // FIXME(const_generics): handle `ConstValue::ByRef` and `ConstValue::Slice`.
603 // FIXME(const_generics): this is wrong, as it is a projection
604 (ConstValue::Unevaluated(a_def_id, a_substs),
605 ConstValue::Unevaluated(b_def_id, b_substs)) if a_def_id == b_def_id => {
607 relation.relate_with_variance(ty::Variance::Invariant, &a_substs, &b_substs)?;
608 Ok(tcx.mk_const(ty::Const {
609 val: ConstValue::Unevaluated(a_def_id, &substs),
614 _ => Err(TypeError::ConstMismatch(expected_found(relation, &a, &b))),
618 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::ExistentialPredicate<'tcx>> {
619 fn relate<R: TypeRelation<'tcx>>(
623 ) -> RelateResult<'tcx, Self> {
624 if a.len() != b.len() {
625 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
628 let tcx = relation.tcx();
629 let v = a.iter().zip(b.iter()).map(|(ep_a, ep_b)| {
630 use crate::ty::ExistentialPredicate::*;
631 match (*ep_a, *ep_b) {
632 (Trait(ref a), Trait(ref b)) => Ok(Trait(relation.relate(a, b)?)),
633 (Projection(ref a), Projection(ref b)) => Ok(Projection(relation.relate(a, b)?)),
634 (AutoTrait(ref a), AutoTrait(ref b)) if a == b => Ok(AutoTrait(*a)),
635 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)))
638 Ok(tcx.mk_existential_predicates(v)?)
642 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
643 fn relate<R: TypeRelation<'tcx>>(
645 a: &ty::ClosureSubsts<'tcx>,
646 b: &ty::ClosureSubsts<'tcx>,
647 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
648 let substs = relate_substs(relation, None, a.substs, b.substs)?;
649 Ok(ty::ClosureSubsts { substs })
653 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
654 fn relate<R: TypeRelation<'tcx>>(
656 a: &ty::GeneratorSubsts<'tcx>,
657 b: &ty::GeneratorSubsts<'tcx>,
658 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
659 let substs = relate_substs(relation, None, a.substs, b.substs)?;
660 Ok(ty::GeneratorSubsts { substs })
664 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
665 fn relate<R: TypeRelation<'tcx>>(
669 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
670 relate_substs(relation, None, a, b)
674 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
675 fn relate<R: TypeRelation<'tcx>>(
677 a: &ty::Region<'tcx>,
678 b: &ty::Region<'tcx>,
679 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
680 relation.regions(*a, *b)
684 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
685 fn relate<R: TypeRelation<'tcx>>(
687 a: &&'tcx ty::Const<'tcx>,
688 b: &&'tcx ty::Const<'tcx>,
689 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
690 relation.consts(*a, *b)
694 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
695 fn relate<R: TypeRelation<'tcx>>(
699 ) -> RelateResult<'tcx, ty::Binder<T>> {
700 relation.binders(a, b)
704 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
705 fn relate<R: TypeRelation<'tcx>>(
709 ) -> RelateResult<'tcx, Rc<T>> {
712 Ok(Rc::new(relation.relate(a, b)?))
716 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
717 fn relate<R: TypeRelation<'tcx>>(
721 ) -> RelateResult<'tcx, Box<T>> {
724 Ok(Box::new(relation.relate(a, b)?))
728 impl<'tcx> Relate<'tcx> for Kind<'tcx> {
729 fn relate<R: TypeRelation<'tcx>>(
733 ) -> RelateResult<'tcx, Kind<'tcx>> {
734 match (a.unpack(), b.unpack()) {
735 (UnpackedKind::Lifetime(a_lt), UnpackedKind::Lifetime(b_lt)) => {
736 Ok(relation.relate(&a_lt, &b_lt)?.into())
738 (UnpackedKind::Type(a_ty), UnpackedKind::Type(b_ty)) => {
739 Ok(relation.relate(&a_ty, &b_ty)?.into())
741 (UnpackedKind::Const(a_ct), UnpackedKind::Const(b_ct)) => {
742 Ok(relation.relate(&a_ct, &b_ct)?.into())
744 (UnpackedKind::Lifetime(unpacked), x) => {
745 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
747 (UnpackedKind::Type(unpacked), x) => {
748 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
750 (UnpackedKind::Const(unpacked), x) => {
751 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
757 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
758 fn relate<R: TypeRelation<'tcx>>(
760 a: &ty::TraitPredicate<'tcx>,
761 b: &ty::TraitPredicate<'tcx>,
762 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
763 Ok(ty::TraitPredicate {
764 trait_ref: relation.relate(&a.trait_ref, &b.trait_ref)?,
769 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
770 fn relate<R: TypeRelation<'tcx>>(
772 a: &ty::ProjectionPredicate<'tcx>,
773 b: &ty::ProjectionPredicate<'tcx>,
774 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
775 Ok(ty::ProjectionPredicate {
776 projection_ty: relation.relate(&a.projection_ty, &b.projection_ty)?,
777 ty: relation.relate(&a.ty, &b.ty)?,
782 impl<'tcx> Relate<'tcx> for traits::WhereClause<'tcx> {
783 fn relate<R: TypeRelation<'tcx>>(
785 a: &traits::WhereClause<'tcx>,
786 b: &traits::WhereClause<'tcx>,
787 ) -> RelateResult<'tcx, traits::WhereClause<'tcx>> {
788 use crate::traits::WhereClause::*;
790 (Implemented(a_pred), Implemented(b_pred)) => {
791 Ok(Implemented(relation.relate(a_pred, b_pred)?))
794 (ProjectionEq(a_pred), ProjectionEq(b_pred)) => {
795 Ok(ProjectionEq(relation.relate(a_pred, b_pred)?))
798 (RegionOutlives(a_pred), RegionOutlives(b_pred)) => {
799 Ok(RegionOutlives(ty::OutlivesPredicate(
800 relation.relate(&a_pred.0, &b_pred.0)?,
801 relation.relate(&a_pred.1, &b_pred.1)?,
805 (TypeOutlives(a_pred), TypeOutlives(b_pred)) => {
806 Ok(TypeOutlives(ty::OutlivesPredicate(
807 relation.relate(&a_pred.0, &b_pred.0)?,
808 relation.relate(&a_pred.1, &b_pred.1)?,
812 _ => Err(TypeError::Mismatch),
817 impl<'tcx> Relate<'tcx> for traits::WellFormed<'tcx> {
818 fn relate<R: TypeRelation<'tcx>>(
820 a: &traits::WellFormed<'tcx>,
821 b: &traits::WellFormed<'tcx>,
822 ) -> RelateResult<'tcx, traits::WellFormed<'tcx>> {
823 use crate::traits::WellFormed::*;
825 (Trait(a_pred), Trait(b_pred)) => Ok(Trait(relation.relate(a_pred, b_pred)?)),
826 (Ty(a_ty), Ty(b_ty)) => Ok(Ty(relation.relate(a_ty, b_ty)?)),
827 _ => Err(TypeError::Mismatch),
832 impl<'tcx> Relate<'tcx> for traits::FromEnv<'tcx> {
833 fn relate<R: TypeRelation<'tcx>>(
835 a: &traits::FromEnv<'tcx>,
836 b: &traits::FromEnv<'tcx>,
837 ) -> RelateResult<'tcx, traits::FromEnv<'tcx>> {
838 use crate::traits::FromEnv::*;
840 (Trait(a_pred), Trait(b_pred)) => Ok(Trait(relation.relate(a_pred, b_pred)?)),
841 (Ty(a_ty), Ty(b_ty)) => Ok(Ty(relation.relate(a_ty, b_ty)?)),
842 _ => Err(TypeError::Mismatch),
847 impl<'tcx> Relate<'tcx> for traits::DomainGoal<'tcx> {
848 fn relate<R: TypeRelation<'tcx>>(
850 a: &traits::DomainGoal<'tcx>,
851 b: &traits::DomainGoal<'tcx>,
852 ) -> RelateResult<'tcx, traits::DomainGoal<'tcx>> {
853 use crate::traits::DomainGoal::*;
855 (Holds(a_wc), Holds(b_wc)) => Ok(Holds(relation.relate(a_wc, b_wc)?)),
856 (WellFormed(a_wf), WellFormed(b_wf)) => Ok(WellFormed(relation.relate(a_wf, b_wf)?)),
857 (FromEnv(a_fe), FromEnv(b_fe)) => Ok(FromEnv(relation.relate(a_fe, b_fe)?)),
859 (Normalize(a_pred), Normalize(b_pred)) => {
860 Ok(Normalize(relation.relate(a_pred, b_pred)?))
863 _ => Err(TypeError::Mismatch),
868 impl<'tcx> Relate<'tcx> for traits::Goal<'tcx> {
869 fn relate<R: TypeRelation<'tcx>>(
871 a: &traits::Goal<'tcx>,
872 b: &traits::Goal<'tcx>,
873 ) -> RelateResult<'tcx, traits::Goal<'tcx>> {
874 use crate::traits::GoalKind::*;
876 (Implies(a_clauses, a_goal), Implies(b_clauses, b_goal)) => {
877 let clauses = relation.relate(a_clauses, b_clauses)?;
878 let goal = relation.relate(a_goal, b_goal)?;
879 Ok(relation.tcx().mk_goal(Implies(clauses, goal)))
882 (And(a_left, a_right), And(b_left, b_right)) => {
883 let left = relation.relate(a_left, b_left)?;
884 let right = relation.relate(a_right, b_right)?;
885 Ok(relation.tcx().mk_goal(And(left, right)))
888 (Not(a_goal), Not(b_goal)) => {
889 let goal = relation.relate(a_goal, b_goal)?;
890 Ok(relation.tcx().mk_goal(Not(goal)))
893 (DomainGoal(a_goal), DomainGoal(b_goal)) => {
894 let goal = relation.relate(a_goal, b_goal)?;
895 Ok(relation.tcx().mk_goal(DomainGoal(goal)))
898 (Quantified(a_qkind, a_goal), Quantified(b_qkind, b_goal))
899 if a_qkind == b_qkind =>
901 let goal = relation.relate(a_goal, b_goal)?;
902 Ok(relation.tcx().mk_goal(Quantified(*a_qkind, goal)))
905 (CannotProve, CannotProve) => Ok(*a),
907 _ => Err(TypeError::Mismatch),
912 impl<'tcx> Relate<'tcx> for traits::Goals<'tcx> {
913 fn relate<R: TypeRelation<'tcx>>(
915 a: &traits::Goals<'tcx>,
916 b: &traits::Goals<'tcx>,
917 ) -> RelateResult<'tcx, traits::Goals<'tcx>> {
918 if a.len() != b.len() {
919 return Err(TypeError::Mismatch);
922 let tcx = relation.tcx();
923 let goals = a.iter().zip(b.iter()).map(|(a, b)| relation.relate(a, b));
924 Ok(tcx.mk_goals(goals)?)
928 impl<'tcx> Relate<'tcx> for traits::Clause<'tcx> {
929 fn relate<R: TypeRelation<'tcx>>(
931 a: &traits::Clause<'tcx>,
932 b: &traits::Clause<'tcx>,
933 ) -> RelateResult<'tcx, traits::Clause<'tcx>> {
934 use crate::traits::Clause::*;
936 (Implies(a_clause), Implies(b_clause)) => {
937 let clause = relation.relate(a_clause, b_clause)?;
941 (ForAll(a_clause), ForAll(b_clause)) => {
942 let clause = relation.relate(a_clause, b_clause)?;
946 _ => Err(TypeError::Mismatch),
951 impl<'tcx> Relate<'tcx> for traits::Clauses<'tcx> {
952 fn relate<R: TypeRelation<'tcx>>(
954 a: &traits::Clauses<'tcx>,
955 b: &traits::Clauses<'tcx>,
956 ) -> RelateResult<'tcx, traits::Clauses<'tcx>> {
957 if a.len() != b.len() {
958 return Err(TypeError::Mismatch);
961 let tcx = relation.tcx();
962 let clauses = a.iter().zip(b.iter()).map(|(a, b)| relation.relate(a, b));
963 Ok(tcx.mk_clauses(clauses)?)
967 impl<'tcx> Relate<'tcx> for traits::ProgramClause<'tcx> {
968 fn relate<R: TypeRelation<'tcx>>(
970 a: &traits::ProgramClause<'tcx>,
971 b: &traits::ProgramClause<'tcx>,
972 ) -> RelateResult<'tcx, traits::ProgramClause<'tcx>> {
973 Ok(traits::ProgramClause {
974 goal: relation.relate(&a.goal, &b.goal)?,
975 hypotheses: relation.relate(&a.hypotheses, &b.hypotheses)?,
976 category: traits::ProgramClauseCategory::Other,
981 impl<'tcx> Relate<'tcx> for traits::Environment<'tcx> {
982 fn relate<R: TypeRelation<'tcx>>(
984 a: &traits::Environment<'tcx>,
985 b: &traits::Environment<'tcx>,
986 ) -> RelateResult<'tcx, traits::Environment<'tcx>> {
987 Ok(traits::Environment {
988 clauses: relation.relate(&a.clauses, &b.clauses)?,
993 impl<'tcx, G> Relate<'tcx> for traits::InEnvironment<'tcx, G>
997 fn relate<R: TypeRelation<'tcx>>(
999 a: &traits::InEnvironment<'tcx, G>,
1000 b: &traits::InEnvironment<'tcx, G>,
1001 ) -> RelateResult<'tcx, traits::InEnvironment<'tcx, G>> {
1002 Ok(traits::InEnvironment {
1003 environment: relation.relate(&a.environment, &b.environment)?,
1004 goal: relation.relate(&a.goal, &b.goal)?,
1009 ///////////////////////////////////////////////////////////////////////////
1012 pub fn expected_found<R, T>(relation: &mut R, a: &T, b: &T) -> ExpectedFound<T>
1014 R: TypeRelation<'tcx>,
1017 expected_found_bool(relation.a_is_expected(), a, b)
1020 pub fn expected_found_bool<T>(a_is_expected: bool,
1029 ExpectedFound {expected: a, found: b}
1031 ExpectedFound {expected: b, found: a}