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