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, Expr, 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 intercrate(&self) -> bool;
28 fn param_env(&self) -> ty::ParamEnv<'tcx>;
30 /// Returns a static string we can use for printouts.
31 fn tag(&self) -> &'static str;
33 /// Returns `true` if the value `a` is the "expected" type in the
34 /// relation. Just affects error messages.
35 fn a_is_expected(&self) -> bool;
37 /// Used during coherence. If called, must emit an always-ambiguous obligation.
38 fn mark_ambiguous(&mut self);
40 fn with_cause<F, R>(&mut self, _cause: Cause, f: F) -> R
42 F: FnOnce(&mut Self) -> R,
47 /// Generic relation routine suitable for most anything.
48 fn relate<T: Relate<'tcx>>(&mut self, a: T, b: T) -> RelateResult<'tcx, T> {
49 Relate::relate(self, a, b)
52 /// Relate the two substitutions for the given item. The default
53 /// is to look up the variance for the item and proceed
55 fn relate_item_substs(
58 a_subst: SubstsRef<'tcx>,
59 b_subst: SubstsRef<'tcx>,
60 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
62 "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
63 item_def_id, a_subst, b_subst
67 let opt_variances = tcx.variances_of(item_def_id);
68 relate_substs_with_variances(self, item_def_id, opt_variances, a_subst, b_subst, true)
71 /// Switch variance for the purpose of relating `a` and `b`.
72 fn relate_with_variance<T: Relate<'tcx>>(
74 variance: ty::Variance,
75 info: ty::VarianceDiagInfo<'tcx>,
78 ) -> RelateResult<'tcx, T>;
80 // Overridable relations. You shouldn't typically call these
81 // directly, instead call `relate()`, which in turn calls
82 // these. This is both more uniform but also allows us to add
83 // additional hooks for other types in the future if needed
84 // without making older code, which called `relate`, obsolete.
86 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>;
92 ) -> RelateResult<'tcx, ty::Region<'tcx>>;
98 ) -> RelateResult<'tcx, ty::Const<'tcx>>;
102 a: ty::Binder<'tcx, T>,
103 b: ty::Binder<'tcx, T>,
104 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
109 pub trait Relate<'tcx>: TypeFoldable<'tcx> + PartialEq + Copy {
110 fn relate<R: TypeRelation<'tcx>>(
114 ) -> RelateResult<'tcx, Self>;
117 ///////////////////////////////////////////////////////////////////////////
120 pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>(
122 a: ty::TypeAndMut<'tcx>,
123 b: ty::TypeAndMut<'tcx>,
125 ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> {
126 debug!("{}.mts({:?}, {:?})", relation.tag(), a, b);
127 if a.mutbl != b.mutbl {
128 Err(TypeError::Mutability)
131 let (variance, info) = match mutbl {
132 ast::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None),
133 ast::Mutability::Mut => {
134 (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 })
137 let ty = relation.relate_with_variance(variance, info, a.ty, b.ty)?;
138 Ok(ty::TypeAndMut { ty, mutbl })
143 pub fn relate_substs<'tcx, R: TypeRelation<'tcx>>(
145 a_subst: SubstsRef<'tcx>,
146 b_subst: SubstsRef<'tcx>,
147 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
148 relation.tcx().mk_substs(iter::zip(a_subst, b_subst).map(|(a, b)| {
149 relation.relate_with_variance(ty::Invariant, ty::VarianceDiagInfo::default(), a, b)
153 pub fn relate_substs_with_variances<'tcx, R: TypeRelation<'tcx>>(
156 variances: &[ty::Variance],
157 a_subst: SubstsRef<'tcx>,
158 b_subst: SubstsRef<'tcx>,
159 fetch_ty_for_diag: bool,
160 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
161 let tcx = relation.tcx();
163 let mut cached_ty = None;
164 let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| {
165 let variance = variances[i];
166 let variance_info = if variance == ty::Invariant && fetch_ty_for_diag {
168 *cached_ty.get_or_insert_with(|| tcx.bound_type_of(ty_def_id).subst(tcx, a_subst));
169 ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() }
171 ty::VarianceDiagInfo::default()
173 relation.relate_with_variance(variance, variance_info, a, b)
176 tcx.mk_substs(params)
179 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
180 fn relate<R: TypeRelation<'tcx>>(
184 ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
185 let tcx = relation.tcx();
187 if a.c_variadic != b.c_variadic {
188 return Err(TypeError::VariadicMismatch(expected_found(
194 let unsafety = relation.relate(a.unsafety, b.unsafety)?;
195 let abi = relation.relate(a.abi, b.abi)?;
197 if a.inputs().len() != b.inputs().len() {
198 return Err(TypeError::ArgCount);
201 let inputs_and_output = iter::zip(a.inputs(), b.inputs())
202 .map(|(&a, &b)| ((a, b), false))
203 .chain(iter::once(((a.output(), b.output()), true)))
204 .map(|((a, b), is_output)| {
206 relation.relate(a, b)
208 relation.relate_with_variance(
210 ty::VarianceDiagInfo::default(),
217 .map(|(i, r)| match r {
218 Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
219 Err(TypeError::ArgumentSorts(exp_found, i))
221 Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
222 Err(TypeError::ArgumentMutability(i))
227 inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
228 c_variadic: a.c_variadic,
235 impl<'tcx> Relate<'tcx> for ty::BoundConstness {
236 fn relate<R: TypeRelation<'tcx>>(
238 a: ty::BoundConstness,
239 b: ty::BoundConstness,
240 ) -> RelateResult<'tcx, ty::BoundConstness> {
242 Err(TypeError::ConstnessMismatch(expected_found(relation, a, b)))
249 impl<'tcx> Relate<'tcx> for ast::Unsafety {
250 fn relate<R: TypeRelation<'tcx>>(
254 ) -> RelateResult<'tcx, ast::Unsafety> {
256 Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
263 impl<'tcx> Relate<'tcx> for abi::Abi {
264 fn relate<R: TypeRelation<'tcx>>(
268 ) -> RelateResult<'tcx, abi::Abi> {
269 if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
273 impl<'tcx> Relate<'tcx> for ty::AliasTy<'tcx> {
274 fn relate<R: TypeRelation<'tcx>>(
276 a: ty::AliasTy<'tcx>,
277 b: ty::AliasTy<'tcx>,
278 ) -> RelateResult<'tcx, ty::AliasTy<'tcx>> {
279 if a.def_id != b.def_id {
280 Err(TypeError::ProjectionMismatched(expected_found(relation, a.def_id, b.def_id)))
282 let substs = relation.relate(a.substs, b.substs)?;
283 Ok(relation.tcx().mk_alias_ty(a.def_id, substs))
288 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
289 fn relate<R: TypeRelation<'tcx>>(
291 a: ty::ExistentialProjection<'tcx>,
292 b: ty::ExistentialProjection<'tcx>,
293 ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
294 if a.def_id != b.def_id {
295 Err(TypeError::ProjectionMismatched(expected_found(relation, a.def_id, b.def_id)))
297 let term = relation.relate_with_variance(
299 ty::VarianceDiagInfo::default(),
303 let substs = relation.relate_with_variance(
305 ty::VarianceDiagInfo::default(),
309 Ok(ty::ExistentialProjection { def_id: a.def_id, substs, term })
314 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
315 fn relate<R: TypeRelation<'tcx>>(
317 a: ty::TraitRef<'tcx>,
318 b: ty::TraitRef<'tcx>,
319 ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
320 // Different traits cannot be related.
321 if a.def_id != b.def_id {
322 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
324 let substs = relate_substs(relation, a.substs, b.substs)?;
325 Ok(relation.tcx().mk_trait_ref(a.def_id, substs))
330 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
331 fn relate<R: TypeRelation<'tcx>>(
333 a: ty::ExistentialTraitRef<'tcx>,
334 b: ty::ExistentialTraitRef<'tcx>,
335 ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
336 // Different traits cannot be related.
337 if a.def_id != b.def_id {
338 Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
340 let substs = relate_substs(relation, a.substs, b.substs)?;
341 Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
346 #[derive(PartialEq, Copy, Debug, Clone, TypeFoldable, TypeVisitable)]
347 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
349 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
350 fn relate<R: TypeRelation<'tcx>>(
352 a: GeneratorWitness<'tcx>,
353 b: GeneratorWitness<'tcx>,
354 ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
355 assert_eq!(a.0.len(), b.0.len());
356 let tcx = relation.tcx();
357 let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
358 Ok(GeneratorWitness(types))
362 impl<'tcx> Relate<'tcx> for ImplSubject<'tcx> {
364 fn relate<R: TypeRelation<'tcx>>(
366 a: ImplSubject<'tcx>,
367 b: ImplSubject<'tcx>,
368 ) -> RelateResult<'tcx, ImplSubject<'tcx>> {
370 (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
371 let trait_ref = ty::TraitRef::relate(relation, trait_ref_a, trait_ref_b)?;
372 Ok(ImplSubject::Trait(trait_ref))
374 (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
375 let ty = Ty::relate(relation, ty_a, ty_b)?;
376 Ok(ImplSubject::Inherent(ty))
378 (ImplSubject::Trait(_), ImplSubject::Inherent(_))
379 | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
380 bug!("can not relate TraitRef and Ty");
386 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
388 fn relate<R: TypeRelation<'tcx>>(
392 ) -> RelateResult<'tcx, Ty<'tcx>> {
397 /// The main "type relation" routine. Note that this does not handle
398 /// inference artifacts, so you should filter those out before calling
400 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
404 ) -> RelateResult<'tcx, Ty<'tcx>> {
405 let tcx = relation.tcx();
406 debug!("super_relate_tys: a={:?} b={:?}", a, b);
407 match (a.kind(), b.kind()) {
408 (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
409 // The caller should handle these cases!
410 bug!("var types encountered in super_relate_tys")
413 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
414 bug!("bound types encountered in super_relate_tys")
417 (&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(tcx.ty_error_with_guaranteed(guar)),
431 (ty::Param(a_p), ty::Param(b_p)) if a_p.index == b_p.index => Ok(a),
433 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
435 (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
436 let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
437 Ok(tcx.mk_adt(a_def, substs))
440 (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
442 (&ty::Dynamic(a_obj, a_region, a_repr), &ty::Dynamic(b_obj, b_region, b_repr))
443 if a_repr == b_repr =>
445 let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
446 relation.relate_with_variance(
448 ty::VarianceDiagInfo::default(),
453 Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr))
456 (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
459 // All Generator types with the same id represent
460 // the (anonymous) type of the same generator expression. So
461 // all of their regions should be equated.
462 let substs = relation.relate(a_substs, b_substs)?;
463 Ok(tcx.mk_generator(a_id, substs, movability))
466 (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
467 // Wrap our types with a temporary GeneratorWitness struct
468 // inside the binder so we can related them
469 let a_types = a_types.map_bound(GeneratorWitness);
470 let b_types = b_types.map_bound(GeneratorWitness);
471 // Then remove the GeneratorWitness for the result
472 let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
473 Ok(tcx.mk_generator_witness(types))
476 (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
477 // All Closure types with the same id represent
478 // the (anonymous) type of the same closure expression. So
479 // all of their regions should be equated.
480 let substs = relation.relate(a_substs, b_substs)?;
481 Ok(tcx.mk_closure(a_id, &substs))
484 (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
485 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
489 (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
490 let r = relation.relate_with_variance(
492 ty::VarianceDiagInfo::default(),
496 let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
497 let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
498 let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
499 Ok(tcx.mk_ref(r, mt))
502 (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
503 let t = relation.relate(a_t, b_t)?;
504 match relation.relate(sz_a, sz_b) {
505 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
507 // Check whether the lengths are both concrete/known values,
508 // but are unequal, for better diagnostics.
510 // It might seem dubious to eagerly evaluate these constants here,
511 // we however cannot end up with errors in `Relate` during both
512 // `type_of` and `predicates_of`. This means that evaluating the
513 // constants should not cause cycle errors here.
514 let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
515 let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
517 (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
518 TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
526 (&ty::Slice(a_t), &ty::Slice(b_t)) => {
527 let t = relation.relate(a_t, b_t)?;
531 (&ty::Tuple(as_), &ty::Tuple(bs)) => {
532 if as_.len() == bs.len() {
533 Ok(tcx.mk_tup(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
534 } else if !(as_.is_empty() || bs.is_empty()) {
535 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
537 Err(TypeError::Sorts(expected_found(relation, a, b)))
541 (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
542 if a_def_id == b_def_id =>
544 let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
545 Ok(tcx.mk_fn_def(a_def_id, substs))
548 (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
549 let fty = relation.relate(a_fty, b_fty)?;
550 Ok(tcx.mk_fn_ptr(fty))
553 // these two are already handled downstream in case of lazy normalization
554 (&ty::Alias(ty::Projection, a_data), &ty::Alias(ty::Projection, b_data)) => {
555 let projection_ty = relation.relate(a_data, b_data)?;
556 Ok(tcx.mk_projection(projection_ty.def_id, projection_ty.substs))
560 &ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, substs: a_substs, .. }),
561 &ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, substs: b_substs, .. }),
562 ) if a_def_id == b_def_id => {
563 if relation.intercrate() {
564 // During coherence, opaque types should be treated as equal to each other, even if their generic params
565 // differ, as they could resolve to the same hidden type, even for different generic params.
566 relation.mark_ambiguous();
569 let opt_variances = tcx.variances_of(a_def_id);
570 let substs = relate_substs_with_variances(
576 false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
578 Ok(tcx.mk_opaque(a_def_id, substs))
582 _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
586 /// The main "const relation" routine. Note that this does not handle
587 /// inference artifacts, so you should filter those out before calling
589 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
591 mut a: ty::Const<'tcx>,
592 mut b: ty::Const<'tcx>,
593 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
594 debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
595 let tcx = relation.tcx();
599 if relation.tcx().features().adt_const_params {
600 a_ty = tcx.normalize_erasing_regions(relation.param_env(), a.ty());
601 b_ty = tcx.normalize_erasing_regions(relation.param_env(), b.ty());
603 a_ty = tcx.erase_regions(a.ty());
604 b_ty = tcx.erase_regions(b.ty());
607 relation.tcx().sess.delay_span_bug(
610 "cannot relate constants ({:?}, {:?}) of different types: {} != {}",
616 // HACK(const_generics): We still need to eagerly evaluate consts when
617 // relating them because during `normalize_param_env_or_error`,
618 // we may relate an evaluated constant in a obligation against
619 // an unnormalized (i.e. unevaluated) const in the param-env.
620 // FIXME(generic_const_exprs): Once we always lazily unify unevaluated constants
621 // these `eval` calls can be removed.
622 if !tcx.features().generic_const_exprs {
623 a = a.eval(tcx, relation.param_env());
624 b = b.eval(tcx, relation.param_env());
627 if tcx.features().generic_const_exprs {
628 a = tcx.expand_abstract_consts(a);
629 b = tcx.expand_abstract_consts(b);
632 // Currently, the values that can be unified are primitive types,
633 // and those that derive both `PartialEq` and `Eq`, corresponding
634 // to structural-match types.
635 let is_match = match (a.kind(), b.kind()) {
636 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
637 // The caller should handle these cases!
638 bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
641 (ty::ConstKind::Error(_), _) => return Ok(a),
642 (_, ty::ConstKind::Error(_)) => return Ok(b),
644 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
645 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
646 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
648 // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
649 // and is the better alternative to waiting until `generic_const_exprs` can
651 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
652 assert_eq!(a.ty(), b.ty());
653 let substs = relation.relate_with_variance(
654 ty::Variance::Invariant,
655 ty::VarianceDiagInfo::default(),
659 return Ok(tcx.mk_const(ty::UnevaluatedConst { def: au.def, substs }, a.ty()));
661 // Before calling relate on exprs, it is necessary to ensure that the nested consts
662 // have identical types.
663 (ty::ConstKind::Expr(ae), ty::ConstKind::Expr(be)) => {
666 // FIXME(generic_const_exprs): is it possible to relate two consts which are not identical
667 // exprs? Should we care about that?
668 let expr = match (ae, be) {
669 (Expr::Binop(a_op, al, ar), Expr::Binop(b_op, bl, br))
670 if a_op == b_op && al.ty() == bl.ty() && ar.ty() == br.ty() =>
672 Expr::Binop(a_op, r.consts(al, bl)?, r.consts(ar, br)?)
674 (Expr::UnOp(a_op, av), Expr::UnOp(b_op, bv))
675 if a_op == b_op && av.ty() == bv.ty() =>
677 Expr::UnOp(a_op, r.consts(av, bv)?)
679 (Expr::Cast(ak, av, at), Expr::Cast(bk, bv, bt))
680 if ak == bk && av.ty() == bv.ty() =>
682 Expr::Cast(ak, r.consts(av, bv)?, r.tys(at, bt)?)
684 (Expr::FunctionCall(af, aa), Expr::FunctionCall(bf, ba))
685 if aa.len() == ba.len()
686 && af.ty() == bf.ty()
690 .all(|(a_arg, b_arg)| a_arg.ty() == b_arg.ty()) =>
692 let func = r.consts(af, bf)?;
693 let mut related_args = Vec::with_capacity(aa.len());
694 for (a_arg, b_arg) in aa.iter().zip(ba.iter()) {
695 related_args.push(r.consts(a_arg, b_arg)?);
697 let related_args = tcx.mk_const_list(related_args.iter());
698 Expr::FunctionCall(func, related_args)
700 _ => return Err(TypeError::ConstMismatch(expected_found(r, a, b))),
702 let kind = ty::ConstKind::Expr(expr);
703 return Ok(tcx.mk_const(kind, a.ty()));
707 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
710 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
711 fn relate<R: TypeRelation<'tcx>>(
715 ) -> RelateResult<'tcx, Self> {
716 let tcx = relation.tcx();
718 // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
719 // We need to perform this deduplication as we sometimes generate duplicate projections
721 let mut a_v: Vec<_> = a.into_iter().collect();
722 let mut b_v: Vec<_> = b.into_iter().collect();
723 // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
724 a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
726 b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
728 if a_v.len() != b_v.len() {
729 return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
732 let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
733 use crate::ty::ExistentialPredicate::*;
734 match (ep_a.skip_binder(), ep_b.skip_binder()) {
735 (Trait(a), Trait(b)) => Ok(ep_a
736 .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
737 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
738 relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
740 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
741 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
744 tcx.mk_poly_existential_predicates(v)
748 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
749 fn relate<R: TypeRelation<'tcx>>(
751 a: ty::ClosureSubsts<'tcx>,
752 b: ty::ClosureSubsts<'tcx>,
753 ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
754 let substs = relate_substs(relation, a.substs, b.substs)?;
755 Ok(ty::ClosureSubsts { substs })
759 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
760 fn relate<R: TypeRelation<'tcx>>(
762 a: ty::GeneratorSubsts<'tcx>,
763 b: ty::GeneratorSubsts<'tcx>,
764 ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
765 let substs = relate_substs(relation, a.substs, b.substs)?;
766 Ok(ty::GeneratorSubsts { substs })
770 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
771 fn relate<R: TypeRelation<'tcx>>(
775 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
776 relate_substs(relation, a, b)
780 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
781 fn relate<R: TypeRelation<'tcx>>(
785 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
786 relation.regions(a, b)
790 impl<'tcx> Relate<'tcx> for ty::Const<'tcx> {
791 fn relate<R: TypeRelation<'tcx>>(
795 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
796 relation.consts(a, b)
800 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
801 fn relate<R: TypeRelation<'tcx>>(
803 a: ty::Binder<'tcx, T>,
804 b: ty::Binder<'tcx, T>,
805 ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
806 relation.binders(a, b)
810 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
811 fn relate<R: TypeRelation<'tcx>>(
815 ) -> RelateResult<'tcx, GenericArg<'tcx>> {
816 match (a.unpack(), b.unpack()) {
817 (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
818 Ok(relation.relate(a_lt, b_lt)?.into())
820 (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
821 Ok(relation.relate(a_ty, b_ty)?.into())
823 (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
824 Ok(relation.relate(a_ct, b_ct)?.into())
826 (GenericArgKind::Lifetime(unpacked), x) => {
827 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
829 (GenericArgKind::Type(unpacked), x) => {
830 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
832 (GenericArgKind::Const(unpacked), x) => {
833 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
839 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
840 fn relate<R: TypeRelation<'tcx>>(
844 ) -> RelateResult<'tcx, ty::ImplPolarity> {
846 Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
853 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
854 fn relate<R: TypeRelation<'tcx>>(
856 a: ty::TraitPredicate<'tcx>,
857 b: ty::TraitPredicate<'tcx>,
858 ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
859 Ok(ty::TraitPredicate {
860 trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
861 constness: relation.relate(a.constness, b.constness)?,
862 polarity: relation.relate(a.polarity, b.polarity)?,
867 impl<'tcx> Relate<'tcx> for Term<'tcx> {
868 fn relate<R: TypeRelation<'tcx>>(
872 ) -> RelateResult<'tcx, Self> {
873 Ok(match (a.unpack(), b.unpack()) {
874 (TermKind::Ty(a), TermKind::Ty(b)) => relation.relate(a, b)?.into(),
875 (TermKind::Const(a), TermKind::Const(b)) => relation.relate(a, b)?.into(),
876 _ => return Err(TypeError::Mismatch),
881 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
882 fn relate<R: TypeRelation<'tcx>>(
884 a: ty::ProjectionPredicate<'tcx>,
885 b: ty::ProjectionPredicate<'tcx>,
886 ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
887 Ok(ty::ProjectionPredicate {
888 projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
889 term: relation.relate(a.term, b.term)?,
894 ///////////////////////////////////////////////////////////////////////////
897 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
899 R: TypeRelation<'tcx>,
901 ExpectedFound::new(relation.a_is_expected(), a, b)