]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/relate.rs
Merge commit '3ae8faff4d46ad92f194c2a4b941c3152a701b31' into clippyup
[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<'tcx, T>,
97         b: ty::Binder<'tcx, T>,
98     ) -> RelateResult<'tcx, ty::Binder<'tcx, 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 = iter::zip(a_subst, 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 = iter::zip(a.inputs(), b.inputs())
174             .map(|(&a, &b)| ((a, b), false))
175             .chain(iter::once(((a.output(), b.output()), true)))
176             .map(|((a, b), is_output)| {
177                 if is_output {
178                     relation.relate(a, b)
179                 } else {
180                     relation.relate_with_variance(ty::Contravariant, a, b)
181                 }
182             })
183             .enumerate()
184             .map(|(i, r)| match r {
185                 Err(TypeError::Sorts(exp_found)) => Err(TypeError::ArgumentSorts(exp_found, i)),
186                 Err(TypeError::Mutability) => Err(TypeError::ArgumentMutability(i)),
187                 r => r,
188             });
189         Ok(ty::FnSig {
190             inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
191             c_variadic: a.c_variadic,
192             unsafety,
193             abi,
194         })
195     }
196 }
197
198 impl<'tcx> Relate<'tcx> for ast::Unsafety {
199     fn relate<R: TypeRelation<'tcx>>(
200         relation: &mut R,
201         a: ast::Unsafety,
202         b: ast::Unsafety,
203     ) -> RelateResult<'tcx, ast::Unsafety> {
204         if a != b {
205             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
206         } else {
207             Ok(a)
208         }
209     }
210 }
211
212 impl<'tcx> Relate<'tcx> for abi::Abi {
213     fn relate<R: TypeRelation<'tcx>>(
214         relation: &mut R,
215         a: abi::Abi,
216         b: abi::Abi,
217     ) -> RelateResult<'tcx, abi::Abi> {
218         if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) }
219     }
220 }
221
222 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
223     fn relate<R: TypeRelation<'tcx>>(
224         relation: &mut R,
225         a: ty::ProjectionTy<'tcx>,
226         b: ty::ProjectionTy<'tcx>,
227     ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> {
228         if a.item_def_id != b.item_def_id {
229             Err(TypeError::ProjectionMismatched(expected_found(
230                 relation,
231                 a.item_def_id,
232                 b.item_def_id,
233             )))
234         } else {
235             let substs = relation.relate(a.substs, b.substs)?;
236             Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs })
237         }
238     }
239 }
240
241 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
242     fn relate<R: TypeRelation<'tcx>>(
243         relation: &mut R,
244         a: ty::ExistentialProjection<'tcx>,
245         b: ty::ExistentialProjection<'tcx>,
246     ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
247         if a.item_def_id != b.item_def_id {
248             Err(TypeError::ProjectionMismatched(expected_found(
249                 relation,
250                 a.item_def_id,
251                 b.item_def_id,
252             )))
253         } else {
254             let ty = relation.relate_with_variance(ty::Invariant, a.ty, b.ty)?;
255             let substs = relation.relate_with_variance(ty::Invariant, a.substs, b.substs)?;
256             Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, ty })
257         }
258     }
259 }
260
261 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
262     fn relate<R: TypeRelation<'tcx>>(
263         relation: &mut R,
264         a: ty::TraitRef<'tcx>,
265         b: ty::TraitRef<'tcx>,
266     ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
267         // Different traits cannot be related.
268         if a.def_id != b.def_id {
269             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
270         } else {
271             let substs = relate_substs(relation, None, a.substs, b.substs)?;
272             Ok(ty::TraitRef { def_id: a.def_id, substs })
273         }
274     }
275 }
276
277 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
278     fn relate<R: TypeRelation<'tcx>>(
279         relation: &mut R,
280         a: ty::ExistentialTraitRef<'tcx>,
281         b: ty::ExistentialTraitRef<'tcx>,
282     ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
283         // Different traits cannot be related.
284         if a.def_id != b.def_id {
285             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
286         } else {
287             let substs = relate_substs(relation, None, a.substs, b.substs)?;
288             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
289         }
290     }
291 }
292
293 #[derive(Copy, Debug, Clone, TypeFoldable)]
294 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
295
296 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
297     fn relate<R: TypeRelation<'tcx>>(
298         relation: &mut R,
299         a: GeneratorWitness<'tcx>,
300         b: GeneratorWitness<'tcx>,
301     ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
302         assert_eq!(a.0.len(), b.0.len());
303         let tcx = relation.tcx();
304         let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
305         Ok(GeneratorWitness(types))
306     }
307 }
308
309 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
310     #[inline]
311     fn relate<R: TypeRelation<'tcx>>(
312         relation: &mut R,
313         a: Ty<'tcx>,
314         b: Ty<'tcx>,
315     ) -> RelateResult<'tcx, Ty<'tcx>> {
316         relation.tys(a, b)
317     }
318 }
319
320 /// The main "type relation" routine. Note that this does not handle
321 /// inference artifacts, so you should filter those out before calling
322 /// it.
323 pub fn super_relate_tys<R: TypeRelation<'tcx>>(
324     relation: &mut R,
325     a: Ty<'tcx>,
326     b: Ty<'tcx>,
327 ) -> RelateResult<'tcx, Ty<'tcx>> {
328     let tcx = relation.tcx();
329     debug!("super_relate_tys: a={:?} b={:?}", a, b);
330     match (a.kind(), b.kind()) {
331         (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
332             // The caller should handle these cases!
333             bug!("var types encountered in super_relate_tys")
334         }
335
336         (ty::Bound(..), _) | (_, ty::Bound(..)) => {
337             bug!("bound types encountered in super_relate_tys")
338         }
339
340         (&ty::Error(_), _) | (_, &ty::Error(_)) => Ok(tcx.ty_error()),
341
342         (&ty::Never, _)
343         | (&ty::Char, _)
344         | (&ty::Bool, _)
345         | (&ty::Int(_), _)
346         | (&ty::Uint(_), _)
347         | (&ty::Float(_), _)
348         | (&ty::Str, _)
349             if a == b =>
350         {
351             Ok(a)
352         }
353
354         (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a),
355
356         (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
357
358         (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
359             let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
360             Ok(tcx.mk_adt(a_def, substs))
361         }
362
363         (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
364
365         (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => {
366             let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
367                 relation.relate_with_variance(ty::Contravariant, a_region, b_region)
368             })?;
369             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
370         }
371
372         (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
373             if a_id == b_id =>
374         {
375             // All Generator types with the same id represent
376             // the (anonymous) type of the same generator expression. So
377             // all of their regions should be equated.
378             let substs = relation.relate(a_substs, b_substs)?;
379             Ok(tcx.mk_generator(a_id, substs, movability))
380         }
381
382         (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
383             // Wrap our types with a temporary GeneratorWitness struct
384             // inside the binder so we can related them
385             let a_types = a_types.map_bound(GeneratorWitness);
386             let b_types = b_types.map_bound(GeneratorWitness);
387             // Then remove the GeneratorWitness for the result
388             let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
389             Ok(tcx.mk_generator_witness(types))
390         }
391
392         (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
393             // All Closure types with the same id represent
394             // the (anonymous) type of the same closure expression. So
395             // all of their regions should be equated.
396             let substs = relation.relate(a_substs, b_substs)?;
397             Ok(tcx.mk_closure(a_id, &substs))
398         }
399
400         (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
401             let mt = relation.relate(a_mt, b_mt)?;
402             Ok(tcx.mk_ptr(mt))
403         }
404
405         (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
406             let r = relation.relate_with_variance(ty::Contravariant, a_r, b_r)?;
407             let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
408             let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
409             let mt = relation.relate(a_mt, b_mt)?;
410             Ok(tcx.mk_ref(r, mt))
411         }
412
413         (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
414             let t = relation.relate(a_t, b_t)?;
415             match relation.relate(sz_a, sz_b) {
416                 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
417                 Err(err) => {
418                     // Check whether the lengths are both concrete/known values,
419                     // but are unequal, for better diagnostics.
420                     //
421                     // It might seem dubious to eagerly evaluate these constants here,
422                     // we however cannot end up with errors in `Relate` during both
423                     // `type_of` and `predicates_of`. This means that evaluating the
424                     // constants should not cause cycle errors here.
425                     let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
426                     let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
427                     match (sz_a, sz_b) {
428                         (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
429                             TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
430                         ),
431                         _ => Err(err),
432                     }
433                 }
434             }
435         }
436
437         (&ty::Slice(a_t), &ty::Slice(b_t)) => {
438             let t = relation.relate(a_t, b_t)?;
439             Ok(tcx.mk_slice(t))
440         }
441
442         (&ty::Tuple(as_), &ty::Tuple(bs)) => {
443             if as_.len() == bs.len() {
444                 Ok(tcx.mk_tup(
445                     iter::zip(as_, bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())),
446                 )?)
447             } else if !(as_.is_empty() || bs.is_empty()) {
448                 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
449             } else {
450                 Err(TypeError::Sorts(expected_found(relation, a, b)))
451             }
452         }
453
454         (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
455             if a_def_id == b_def_id =>
456         {
457             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
458             Ok(tcx.mk_fn_def(a_def_id, substs))
459         }
460
461         (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
462             let fty = relation.relate(a_fty, b_fty)?;
463             Ok(tcx.mk_fn_ptr(fty))
464         }
465
466         // these two are already handled downstream in case of lazy normalization
467         (&ty::Projection(a_data), &ty::Projection(b_data)) => {
468             let projection_ty = relation.relate(a_data, b_data)?;
469             Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
470         }
471
472         (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
473             if a_def_id == b_def_id =>
474         {
475             let substs = relate_substs(relation, None, a_substs, b_substs)?;
476             Ok(tcx.mk_opaque(a_def_id, substs))
477         }
478
479         _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
480     }
481 }
482
483 /// The main "const relation" routine. Note that this does not handle
484 /// inference artifacts, so you should filter those out before calling
485 /// it.
486 pub fn super_relate_consts<R: TypeRelation<'tcx>>(
487     relation: &mut R,
488     a: &'tcx ty::Const<'tcx>,
489     b: &'tcx ty::Const<'tcx>,
490 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
491     debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
492     let tcx = relation.tcx();
493
494     // FIXME(oli-obk): once const generics can have generic types, this assertion
495     // will likely get triggered. Move to `normalize_erasing_regions` at that point.
496     let a_ty = tcx.erase_regions(a.ty);
497     let b_ty = tcx.erase_regions(b.ty);
498     if a_ty != b_ty {
499         relation.tcx().sess.delay_span_bug(
500             DUMMY_SP,
501             &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty),
502         );
503     }
504
505     let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env());
506     let a = eagerly_eval(a);
507     let b = eagerly_eval(b);
508
509     // Currently, the values that can be unified are primitive types,
510     // and those that derive both `PartialEq` and `Eq`, corresponding
511     // to structural-match types.
512     let is_match = match (a.val, b.val) {
513         (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
514             // The caller should handle these cases!
515             bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
516         }
517
518         (ty::ConstKind::Error(_), _) => return Ok(a),
519         (_, ty::ConstKind::Error(_)) => return Ok(b),
520
521         (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
522         (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
523         (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
524             check_const_value_eq(relation, a_val, b_val, a, b)?
525         }
526
527         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
528             if tcx.features().const_evaluatable_checked =>
529         {
530             tcx.try_unify_abstract_consts(((au.def, au.substs), (bu.def, bu.substs)))
531         }
532
533         // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
534         // and is the better alternative to waiting until `const_evaluatable_checked` can
535         // be stabilized.
536         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
537             if au.def == bu.def && au.promoted == bu.promoted =>
538         {
539             let substs =
540                 relation.relate_with_variance(ty::Variance::Invariant, au.substs, bu.substs)?;
541             return Ok(tcx.mk_const(ty::Const {
542                 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
543                     def: au.def,
544                     substs,
545                     promoted: au.promoted,
546                 }),
547                 ty: a.ty,
548             }));
549         }
550         _ => false,
551     };
552     if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
553 }
554
555 fn check_const_value_eq<R: TypeRelation<'tcx>>(
556     relation: &mut R,
557     a_val: ConstValue<'tcx>,
558     b_val: ConstValue<'tcx>,
559     // FIXME(oli-obk): these arguments should go away with valtrees
560     a: &'tcx ty::Const<'tcx>,
561     b: &'tcx ty::Const<'tcx>,
562     // FIXME(oli-obk): this should just be `bool` with valtrees
563 ) -> RelateResult<'tcx, bool> {
564     let tcx = relation.tcx();
565     Ok(match (a_val, b_val) {
566         (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
567             a_val == b_val
568         }
569         (ConstValue::Scalar(Scalar::Ptr(a_val)), ConstValue::Scalar(Scalar::Ptr(b_val))) => {
570             a_val == b_val
571                 || match (tcx.global_alloc(a_val.alloc_id), tcx.global_alloc(b_val.alloc_id)) {
572                     (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
573                         a_instance == b_instance
574                     }
575                     _ => false,
576                 }
577         }
578
579         (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
580             get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
581         }
582
583         (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
584             let a_destructured = tcx.destructure_const(relation.param_env().and(a));
585             let b_destructured = tcx.destructure_const(relation.param_env().and(b));
586
587             // Both the variant and each field have to be equal.
588             if a_destructured.variant == b_destructured.variant {
589                 for (a_field, b_field) in iter::zip(a_destructured.fields, b_destructured.fields) {
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<'tcx, 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 = iter::zip(a_v, b_v).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(ep_a
629                     .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
630                 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
631                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
632                 ))),
633                 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
634                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
635             }
636         });
637         tcx.mk_poly_existential_predicates(v)
638     }
639 }
640
641 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
642     fn relate<R: TypeRelation<'tcx>>(
643         relation: &mut R,
644         a: ty::ClosureSubsts<'tcx>,
645         b: ty::ClosureSubsts<'tcx>,
646     ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
647         let substs = relate_substs(relation, None, a.substs, b.substs)?;
648         Ok(ty::ClosureSubsts { substs })
649     }
650 }
651
652 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
653     fn relate<R: TypeRelation<'tcx>>(
654         relation: &mut R,
655         a: ty::GeneratorSubsts<'tcx>,
656         b: ty::GeneratorSubsts<'tcx>,
657     ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
658         let substs = relate_substs(relation, None, a.substs, b.substs)?;
659         Ok(ty::GeneratorSubsts { substs })
660     }
661 }
662
663 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
664     fn relate<R: TypeRelation<'tcx>>(
665         relation: &mut R,
666         a: SubstsRef<'tcx>,
667         b: SubstsRef<'tcx>,
668     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
669         relate_substs(relation, None, a, b)
670     }
671 }
672
673 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
674     fn relate<R: TypeRelation<'tcx>>(
675         relation: &mut R,
676         a: ty::Region<'tcx>,
677         b: ty::Region<'tcx>,
678     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
679         relation.regions(a, b)
680     }
681 }
682
683 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
684     fn relate<R: TypeRelation<'tcx>>(
685         relation: &mut R,
686         a: &'tcx ty::Const<'tcx>,
687         b: &'tcx ty::Const<'tcx>,
688     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
689         relation.consts(a, b)
690     }
691 }
692
693 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
694     fn relate<R: TypeRelation<'tcx>>(
695         relation: &mut R,
696         a: ty::Binder<'tcx, T>,
697         b: ty::Binder<'tcx, T>,
698     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
699         relation.binders(a, b)
700     }
701 }
702
703 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
704     fn relate<R: TypeRelation<'tcx>>(
705         relation: &mut R,
706         a: GenericArg<'tcx>,
707         b: GenericArg<'tcx>,
708     ) -> RelateResult<'tcx, GenericArg<'tcx>> {
709         match (a.unpack(), b.unpack()) {
710             (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
711                 Ok(relation.relate(a_lt, b_lt)?.into())
712             }
713             (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
714                 Ok(relation.relate(a_ty, b_ty)?.into())
715             }
716             (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
717                 Ok(relation.relate(a_ct, b_ct)?.into())
718             }
719             (GenericArgKind::Lifetime(unpacked), x) => {
720                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
721             }
722             (GenericArgKind::Type(unpacked), x) => {
723                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
724             }
725             (GenericArgKind::Const(unpacked), x) => {
726                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
727             }
728         }
729     }
730 }
731
732 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
733     fn relate<R: TypeRelation<'tcx>>(
734         relation: &mut R,
735         a: ty::TraitPredicate<'tcx>,
736         b: ty::TraitPredicate<'tcx>,
737     ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
738         Ok(ty::TraitPredicate { trait_ref: relation.relate(a.trait_ref, b.trait_ref)? })
739     }
740 }
741
742 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
743     fn relate<R: TypeRelation<'tcx>>(
744         relation: &mut R,
745         a: ty::ProjectionPredicate<'tcx>,
746         b: ty::ProjectionPredicate<'tcx>,
747     ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
748         Ok(ty::ProjectionPredicate {
749             projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
750             ty: relation.relate(a.ty, b.ty)?,
751         })
752     }
753 }
754
755 ///////////////////////////////////////////////////////////////////////////
756 // Error handling
757
758 pub fn expected_found<R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
759 where
760     R: TypeRelation<'tcx>,
761 {
762     expected_found_bool(relation.a_is_expected(), a, b)
763 }
764
765 pub fn expected_found_bool<T>(a_is_expected: bool, a: T, b: T) -> ExpectedFound<T> {
766     if a_is_expected {
767         ExpectedFound { expected: a, found: b }
768     } else {
769         ExpectedFound { expected: b, found: a }
770     }
771 }