]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/relate.rs
Rollup merge of #82525 - RalfJung:unaligned-ref-warn, r=petrochenkov
[rust.git] / compiler / rustc_middle / src / ty / relate.rs
1 //! Generalized type relating mechanism.
2 //!
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.
6
7 use crate::mir::interpret::{get_slice_bytes, ConstValue, GlobalAlloc, Scalar};
8 use crate::ty::error::{ExpectedFound, TypeError};
9 use crate::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
10 use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
11 use rustc_hir as ast;
12 use rustc_hir::def_id::DefId;
13 use rustc_span::DUMMY_SP;
14 use rustc_target::spec::abi;
15 use std::iter;
16
17 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
18
19 #[derive(Clone, Debug)]
20 pub enum Cause {
21     ExistentialRegionBound, // relating an existential region bound
22 }
23
24 pub trait TypeRelation<'tcx>: Sized {
25     fn tcx(&self) -> TyCtxt<'tcx>;
26
27     fn param_env(&self) -> ty::ParamEnv<'tcx>;
28
29     /// Returns a static string we can use for printouts.
30     fn tag(&self) -> &'static str;
31
32     /// Returns `true` if the value `a` is the "expected" type in the
33     /// relation. Just affects error messages.
34     fn a_is_expected(&self) -> bool;
35
36     fn with_cause<F, R>(&mut self, _cause: Cause, f: F) -> R
37     where
38         F: FnOnce(&mut Self) -> R,
39     {
40         f(self)
41     }
42
43     /// Generic relation routine suitable for most anything.
44     fn relate<T: Relate<'tcx>>(&mut self, a: T, b: T) -> RelateResult<'tcx, T> {
45         Relate::relate(self, a, b)
46     }
47
48     /// Relate the two substitutions for the given item. The default
49     /// is to look up the variance for the item and proceed
50     /// accordingly.
51     fn relate_item_substs(
52         &mut self,
53         item_def_id: DefId,
54         a_subst: SubstsRef<'tcx>,
55         b_subst: SubstsRef<'tcx>,
56     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
57         debug!(
58             "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
59             item_def_id, a_subst, b_subst
60         );
61
62         let opt_variances = self.tcx().variances_of(item_def_id);
63         relate_substs(self, Some(opt_variances), a_subst, b_subst)
64     }
65
66     /// Switch variance for the purpose of relating `a` and `b`.
67     fn relate_with_variance<T: Relate<'tcx>>(
68         &mut self,
69         variance: ty::Variance,
70         a: T,
71         b: T,
72     ) -> RelateResult<'tcx, T>;
73
74     // Overridable relations. You shouldn't typically call these
75     // directly, instead call `relate()`, which in turn calls
76     // these. This is both more uniform but also allows us to add
77     // additional hooks for other types in the future if needed
78     // without making older code, which called `relate`, obsolete.
79
80     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>>;
81
82     fn regions(
83         &mut self,
84         a: ty::Region<'tcx>,
85         b: ty::Region<'tcx>,
86     ) -> RelateResult<'tcx, ty::Region<'tcx>>;
87
88     fn consts(
89         &mut self,
90         a: &'tcx ty::Const<'tcx>,
91         b: &'tcx ty::Const<'tcx>,
92     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>>;
93
94     fn binders<T>(
95         &mut self,
96         a: ty::Binder<T>,
97         b: ty::Binder<T>,
98     ) -> RelateResult<'tcx, ty::Binder<T>>
99     where
100         T: Relate<'tcx>;
101 }
102
103 pub trait Relate<'tcx>: TypeFoldable<'tcx> + Copy {
104     fn relate<R: TypeRelation<'tcx>>(
105         relation: &mut R,
106         a: Self,
107         b: Self,
108     ) -> RelateResult<'tcx, Self>;
109 }
110
111 ///////////////////////////////////////////////////////////////////////////
112 // Relate impls
113
114 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
115     fn relate<R: TypeRelation<'tcx>>(
116         relation: &mut R,
117         a: ty::TypeAndMut<'tcx>,
118         b: ty::TypeAndMut<'tcx>,
119     ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> {
120         debug!("{}.mts({:?}, {:?})", relation.tag(), a, b);
121         if a.mutbl != b.mutbl {
122             Err(TypeError::Mutability)
123         } else {
124             let mutbl = a.mutbl;
125             let variance = match mutbl {
126                 ast::Mutability::Not => ty::Covariant,
127                 ast::Mutability::Mut => ty::Invariant,
128             };
129             let ty = relation.relate_with_variance(variance, a.ty, b.ty)?;
130             Ok(ty::TypeAndMut { ty, mutbl })
131         }
132     }
133 }
134
135 pub fn relate_substs<R: TypeRelation<'tcx>>(
136     relation: &mut R,
137     variances: Option<&[ty::Variance]>,
138     a_subst: SubstsRef<'tcx>,
139     b_subst: SubstsRef<'tcx>,
140 ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
141     let tcx = relation.tcx();
142
143     let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
144         let variance = variances.map_or(ty::Invariant, |v| v[i]);
145         relation.relate_with_variance(variance, a, b)
146     });
147
148     tcx.mk_substs(params)
149 }
150
151 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
152     fn relate<R: TypeRelation<'tcx>>(
153         relation: &mut R,
154         a: ty::FnSig<'tcx>,
155         b: ty::FnSig<'tcx>,
156     ) -> RelateResult<'tcx, ty::FnSig<'tcx>> {
157         let tcx = relation.tcx();
158
159         if a.c_variadic != b.c_variadic {
160             return Err(TypeError::VariadicMismatch(expected_found(
161                 relation,
162                 a.c_variadic,
163                 b.c_variadic,
164             )));
165         }
166         let unsafety = relation.relate(a.unsafety, b.unsafety)?;
167         let abi = relation.relate(a.abi, b.abi)?;
168
169         if a.inputs().len() != b.inputs().len() {
170             return Err(TypeError::ArgCount);
171         }
172
173         let inputs_and_output = a
174             .inputs()
175             .iter()
176             .cloned()
177             .zip(b.inputs().iter().cloned())
178             .map(|x| (x, false))
179             .chain(iter::once(((a.output(), b.output()), true)))
180             .map(|((a, b), is_output)| {
181                 if is_output {
182                     relation.relate(a, b)
183                 } else {
184                     relation.relate_with_variance(ty::Contravariant, a, b)
185                 }
186             });
187         Ok(ty::FnSig {
188             inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
189             c_variadic: a.c_variadic,
190             unsafety,
191             abi,
192         })
193     }
194 }
195
196 impl<'tcx> Relate<'tcx> for ast::Unsafety {
197     fn relate<R: TypeRelation<'tcx>>(
198         relation: &mut R,
199         a: ast::Unsafety,
200         b: ast::Unsafety,
201     ) -> RelateResult<'tcx, ast::Unsafety> {
202         if a != b {
203             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
204         } else {
205             Ok(a)
206         }
207     }
208 }
209
210 impl<'tcx> Relate<'tcx> for abi::Abi {
211     fn relate<R: TypeRelation<'tcx>>(
212         relation: &mut R,
213         a: abi::Abi,
214         b: abi::Abi,
215     ) -> RelateResult<'tcx, abi::Abi> {
216         if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
217     }
218 }
219
220 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
221     fn relate<R: TypeRelation<'tcx>>(
222         relation: &mut R,
223         a: ty::ProjectionTy<'tcx>,
224         b: ty::ProjectionTy<'tcx>,
225     ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
226         if a.item_def_id != b.item_def_id {
227             Err(TypeError::ProjectionMismatched(expected_found(
228                 relation,
229                 a.item_def_id,
230                 b.item_def_id,
231             )))
232         } else {
233             let substs = relation.relate(a.substs, b.substs)?;
234             Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
235         }
236     }
237 }
238
239 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
240     fn relate<R: TypeRelation<'tcx>>(
241         relation: &mut R,
242         a: ty::ExistentialProjection<'tcx>,
243         b: ty::ExistentialProjection<'tcx>,
244     ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
245         if a.item_def_id != b.item_def_id {
246             Err(TypeError::ProjectionMismatched(expected_found(
247                 relation,
248                 a.item_def_id,
249                 b.item_def_id,
250             )))
251         } else {
252             let ty = relation.relate_with_variance(ty::Invariant, a.ty, b.ty)?;
253             let substs = relation.relate_with_variance(ty::Invariant, a.substs, b.substs)?;
254             Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, ty })
255         }
256     }
257 }
258
259 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
260     fn relate<R: TypeRelation<'tcx>>(
261         relation: &mut R,
262         a: ty::TraitRef<'tcx>,
263         b: ty::TraitRef<'tcx>,
264     ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
265         // Different traits cannot be related.
266         if a.def_id != b.def_id {
267             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
268         } else {
269             let substs = relate_substs(relation, None, a.substs, b.substs)?;
270             Ok(ty::TraitRef { def_id: a.def_id, substs })
271         }
272     }
273 }
274
275 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
276     fn relate<R: TypeRelation<'tcx>>(
277         relation: &mut R,
278         a: ty::ExistentialTraitRef<'tcx>,
279         b: ty::ExistentialTraitRef<'tcx>,
280     ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
281         // Different traits cannot be related.
282         if a.def_id != b.def_id {
283             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
284         } else {
285             let substs = relate_substs(relation, None, a.substs, b.substs)?;
286             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
287         }
288     }
289 }
290
291 #[derive(Copy, Debug, Clone, TypeFoldable)]
292 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
293
294 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
295     fn relate<R: TypeRelation<'tcx>>(
296         relation: &mut R,
297         a: GeneratorWitness<'tcx>,
298         b: GeneratorWitness<'tcx>,
299     ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
300         assert_eq!(a.0.len(), b.0.len());
301         let tcx = relation.tcx();
302         let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
303         Ok(GeneratorWitness(types))
304     }
305 }
306
307 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
308     #[inline]
309     fn relate<R: TypeRelation<'tcx>>(
310         relation: &mut R,
311         a: Ty<'tcx>,
312         b: Ty<'tcx>,
313     ) -> RelateResult<'tcx, Ty<'tcx>> {
314         relation.tys(a, b)
315     }
316 }
317
318 /// The main "type relation" routine. Note that this does not handle
319 /// inference artifacts, so you should filter those out before calling
320 /// it.
321 pub fn super_relate_tys<R: TypeRelation<'tcx>>(
322     relation: &mut R,
323     a: Ty<'tcx>,
324     b: Ty<'tcx>,
325 ) -> RelateResult<'tcx, Ty<'tcx>> {
326     let tcx = relation.tcx();
327     debug!("super_relate_tys: a={:?} b={:?}", a, b);
328     match (a.kind(), b.kind()) {
329         (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
330             // The caller should handle these cases!
331             bug!("var types encountered in super_relate_tys")
332         }
333
334         (ty::Bound(..), _) | (_, ty::Bound(..)) => {
335             bug!("bound types encountered in super_relate_tys")
336         }
337
338         (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
339
340         (&ty::Never, _)
341         | (&ty::Char, _)
342         | (&ty::Bool, _)
343         | (&ty::Int(_), _)
344         | (&ty::Uint(_), _)
345         | (&ty::Float(_), _)
346         | (&ty::Str, _)
347             if a == b =>
348         {
349             Ok(a)
350         }
351
352         (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
353
354         (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
355
356         (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
357             let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
358             Ok(tcx.mk_adt(a_def, substs))
359         }
360
361         (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
362
363         (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
364             let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
365                 relation.relate_with_variance(ty::Contravariant, a_region, b_region)
366             })?;
367             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
368         }
369
370         (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
371             if a_id == b_id =>
372         {
373             // All Generator types with the same id represent
374             // the (anonymous) type of the same generator expression. So
375             // all of their regions should be equated.
376             let substs = relation.relate(a_substs, b_substs)?;
377             Ok(tcx.mk_generator(a_id, substs, movability))
378         }
379
380         (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
381             // Wrap our types with a temporary GeneratorWitness struct
382             // inside the binder so we can related them
383             let a_types = a_types.map_bound(GeneratorWitness);
384             let b_types = b_types.map_bound(GeneratorWitness);
385             // Then remove the GeneratorWitness for the result
386             let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
387             Ok(tcx.mk_generator_witness(types))
388         }
389
390         (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
391             // All Closure types with the same id represent
392             // the (anonymous) type of the same closure expression. So
393             // all of their regions should be equated.
394             let substs = relation.relate(a_substs, b_substs)?;
395             Ok(tcx.mk_closure(a_id, &substs))
396         }
397
398         (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
399             let mt = relation.relate(a_mt, b_mt)?;
400             Ok(tcx.mk_ptr(mt))
401         }
402
403         (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
404             let r = relation.relate_with_variance(ty::Contravariant, a_r, b_r)?;
405             let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
406             let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
407             let mt = relation.relate(a_mt, b_mt)?;
408             Ok(tcx.mk_ref(r, mt))
409         }
410
411         (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
412             let t = relation.relate(a_t, b_t)?;
413             match relation.relate(sz_a, sz_b) {
414                 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
415                 Err(err) => {
416                     // Check whether the lengths are both concrete/known values,
417                     // but are unequal, for better diagnostics.
418                     //
419                     // It might seem dubious to eagerly evaluate these constants here,
420                     // we however cannot end up with errors in `Relate` during both
421                     // `type_of` and `predicates_of`. This means that evaluating the
422                     // constants should not cause cycle errors here.
423                     let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
424                     let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
425                     match (sz_a, sz_b) {
426                         (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
427                             TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
428                         ),
429                         _ => Err(err),
430                     }
431                 }
432             }
433         }
434
435         (&ty::Slice(a_t), &ty::Slice(b_t)) => {
436             let t = relation.relate(a_t, b_t)?;
437             Ok(tcx.mk_slice(t))
438         }
439
440         (&ty::Tuple(as_), &ty::Tuple(bs)) => {
441             if as_.len() == bs.len() {
442                 Ok(tcx.mk_tup(
443                     as_.iter().zip(bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())),
444                 )?)
445             } else if !(as_.is_empty() || bs.is_empty()) {
446                 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
447             } else {
448                 Err(TypeError::Sorts(expected_found(relation, a, b)))
449             }
450         }
451
452         (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
453             if a_def_id == b_def_id =>
454         {
455             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
456             Ok(tcx.mk_fn_def(a_def_id, substs))
457         }
458
459         (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
460             let fty = relation.relate(a_fty, b_fty)?;
461             Ok(tcx.mk_fn_ptr(fty))
462         }
463
464         // these two are already handled downstream in case of lazy normalization
465         (&ty::Projection(a_data), &ty::Projection(b_data)) => {
466             let projection_ty = relation.relate(a_data, b_data)?;
467             Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
468         }
469
470         (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
471             if a_def_id == b_def_id =>
472         {
473             let substs = relate_substs(relation, None, a_substs, b_substs)?;
474             Ok(tcx.mk_opaque(a_def_id, substs))
475         }
476
477         _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
478     }
479 }
480
481 /// The main "const relation" routine. Note that this does not handle
482 /// inference artifacts, so you should filter those out before calling
483 /// it.
484 pub fn super_relate_consts<R: TypeRelation<'tcx>>(
485     relation: &mut R,
486     a: &'tcx ty::Const<'tcx>,
487     b: &'tcx ty::Const<'tcx>,
488 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
489     debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
490     let tcx = relation.tcx();
491
492     // FIXME(oli-obk): once const generics can have generic types, this assertion
493     // will likely get triggered. Move to `normalize_erasing_regions` at that point.
494     let a_ty = tcx.erase_regions(a.ty);
495     let b_ty = tcx.erase_regions(b.ty);
496     if a_ty != b_ty {
497         relation.tcx().sess.delay_span_bug(
498             DUMMY_SP,
499             &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
500         );
501     }
502
503     let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env());
504     let a = eagerly_eval(a);
505     let b = eagerly_eval(b);
506
507     // Currently, the values that can be unified are primitive types,
508     // and those that derive both `PartialEq` and `Eq`, corresponding
509     // to structural-match types.
510     let is_match = match (a.val, b.val) {
511         (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
512             // The caller should handle these cases!
513             bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
514         }
515
516         (ty::ConstKind::Error(_), _) => return Ok(a),
517         (_, ty::ConstKind::Error(_)) => return Ok(b),
518
519         (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
520         (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
521         (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
522             check_const_value_eq(relation, a_val, b_val, a, b)?
523         }
524
525         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
526             if tcx.features().const_evaluatable_checked =>
527         {
528             tcx.try_unify_abstract_consts(((au.def, au.substs), (bu.def, bu.substs)))
529         }
530
531         // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
532         // and is the better alternative to waiting until `const_evaluatable_checked` can
533         // be stabilized.
534         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
535             if au.def == bu.def && au.promoted == bu.promoted =>
536         {
537             let substs =
538                 relation.relate_with_variance(ty::Variance::Invariant, au.substs, bu.substs)?;
539             return Ok(tcx.mk_const(ty::Const {
540                 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
541                     def: au.def,
542                     substs,
543                     promoted: au.promoted,
544                 }),
545                 ty: a.ty,
546             }));
547         }
548         _ => false,
549     };
550     if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
551 }
552
553 fn check_const_value_eq<R: TypeRelation<'tcx>>(
554     relation: &mut R,
555     a_val: ConstValue<'tcx>,
556     b_val: ConstValue<'tcx>,
557     // FIXME(oli-obk): these arguments should go away with valtrees
558     a: &'tcx ty::Const<'tcx>,
559     b: &'tcx ty::Const<'tcx>,
560     // FIXME(oli-obk): this should just be `bool` with valtrees
561 ) -> RelateResult<'tcx, bool> {
562     let tcx = relation.tcx();
563     Ok(match (a_val, b_val) {
564         (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
565             a_val == b_val
566         }
567         (ConstValue::Scalar(Scalar::Ptr(a_val)), ConstValue::Scalar(Scalar::Ptr(b_val))) => {
568             a_val == b_val
569                 || match (tcx.global_alloc(a_val.alloc_id), tcx.global_alloc(b_val.alloc_id)) {
570                     (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
571                         a_instance == b_instance
572                     }
573                     _ => false,
574                 }
575         }
576
577         (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
578             get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
579         }
580
581         (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
582             let a_destructured = tcx.destructure_const(relation.param_env().and(a));
583             let b_destructured = tcx.destructure_const(relation.param_env().and(b));
584
585             // Both the variant and each field have to be equal.
586             if a_destructured.variant == b_destructured.variant {
587                 for (a_field, b_field) in
588                     a_destructured.fields.iter().zip(b_destructured.fields.iter())
589                 {
590                     relation.consts(a_field, b_field)?;
591                 }
592
593                 true
594             } else {
595                 false
596             }
597         }
598
599         _ => false,
600     })
601 }
602
603 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>> {
604     fn relate<R: TypeRelation<'tcx>>(
605         relation: &mut R,
606         a: Self,
607         b: Self,
608     ) -> RelateResult<'tcx, Self> {
609         let tcx = relation.tcx();
610
611         // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
612         // We need to perform this deduplication as we sometimes generate duplicate projections
613         // in `a`.
614         let mut a_v: Vec<_> = a.into_iter().collect();
615         let mut b_v: Vec<_> = b.into_iter().collect();
616         // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
617         a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
618         a_v.dedup();
619         b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
620         b_v.dedup();
621         if a_v.len() != b_v.len() {
622             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
623         }
624
625         let v = a_v.into_iter().zip(b_v.into_iter()).map(|(ep_a, ep_b)| {
626             use crate::ty::ExistentialPredicate::*;
627             match (ep_a.skip_binder(), ep_b.skip_binder()) {
628                 (Trait(a), Trait(b)) => Ok(ty::Binder::bind(Trait(
629                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
630                 ))),
631                 (Projection(a), Projection(b)) => Ok(ty::Binder::bind(Projection(
632                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
633                 ))),
634                 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
635                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
636             }
637         });
638         tcx.mk_poly_existential_predicates(v)
639     }
640 }
641
642 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
643     fn relate<R: TypeRelation<'tcx>>(
644         relation: &mut R,
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 })
650     }
651 }
652
653 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
654     fn relate<R: TypeRelation<'tcx>>(
655         relation: &mut R,
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 })
661     }
662 }
663
664 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
665     fn relate<R: TypeRelation<'tcx>>(
666         relation: &mut R,
667         a: SubstsRef<'tcx>,
668         b: SubstsRef<'tcx>,
669     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
670         relate_substs(relation, None, a, b)
671     }
672 }
673
674 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
675     fn relate<R: TypeRelation<'tcx>>(
676         relation: &mut R,
677         a: ty::Region<'tcx>,
678         b: ty::Region<'tcx>,
679     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
680         relation.regions(a, b)
681     }
682 }
683
684 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
685     fn relate<R: TypeRelation<'tcx>>(
686         relation: &mut R,
687         a: &'tcx ty::Const<'tcx>,
688         b: &'tcx ty::Const<'tcx>,
689     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
690         relation.consts(a, b)
691     }
692 }
693
694 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
695     fn relate<R: TypeRelation<'tcx>>(
696         relation: &mut R,
697         a: ty::Binder<T>,
698         b: ty::Binder<T>,
699     ) -> RelateResult<'tcx, ty::Binder<T>> {
700         relation.binders(a, b)
701     }
702 }
703
704 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
705     fn relate<R: TypeRelation<'tcx>>(
706         relation: &mut R,
707         a: GenericArg<'tcx>,
708         b: GenericArg<'tcx>,
709     ) -> RelateResult<'tcx, GenericArg<'tcx>> {
710         match (a.unpack(), b.unpack()) {
711             (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
712                 Ok(relation.relate(a_lt, b_lt)?.into())
713             }
714             (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
715                 Ok(relation.relate(a_ty, b_ty)?.into())
716             }
717             (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
718                 Ok(relation.relate(a_ct, b_ct)?.into())
719             }
720             (GenericArgKind::Lifetime(unpacked), x) => {
721                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
722             }
723             (GenericArgKind::Type(unpacked), x) => {
724                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
725             }
726             (GenericArgKind::Const(unpacked), x) => {
727                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
728             }
729         }
730     }
731 }
732
733 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
734     fn relate<R: TypeRelation<'tcx>>(
735         relation: &mut R,
736         a: ty::TraitPredicate<'tcx>,
737         b: ty::TraitPredicate<'tcx>,
738     ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
739         Ok(ty::TraitPredicate { trait_ref: relation.relate(a.trait_ref, b.trait_ref)? })
740     }
741 }
742
743 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
744     fn relate<R: TypeRelation<'tcx>>(
745         relation: &mut R,
746         a: ty::ProjectionPredicate<'tcx>,
747         b: ty::ProjectionPredicate<'tcx>,
748     ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
749         Ok(ty::ProjectionPredicate {
750             projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
751             ty: relation.relate(a.ty, b.ty)?,
752         })
753     }
754 }
755
756 ///////////////////////////////////////////////////////////////////////////
757 // Error handling
758
759 pub fn expected_found<R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
760 where
761     R: TypeRelation<'tcx>,
762 {
763     expected_found_bool(relation.a_is_expected(), a, b)
764 }
765
766 pub fn expected_found_bool<T>(a_is_expected: bool, a: T, b: T) -> ExpectedFound<T> {
767     if a_is_expected {
768         ExpectedFound { expected: a, found: b }
769     } else {
770         ExpectedFound { expected: b, found: a }
771     }
772 }