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