]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/relate.rs
Rollup merge of #83338 - asquared31415:asm-syntax-test-fix, r=Dylan-DPC
[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         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
535             if tcx.features().const_evaluatable_checked && !relation.visit_ct_substs() =>
536         {
537             tcx.try_unify_abstract_consts(((au.def, au.substs), (bu.def, bu.substs)))
538         }
539
540         // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
541         // and is the better alternative to waiting until `const_evaluatable_checked` can
542         // be stabilized.
543         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu))
544             if au.def == bu.def && au.promoted == bu.promoted =>
545         {
546             let substs =
547                 relation.relate_with_variance(ty::Variance::Invariant, au.substs, bu.substs)?;
548             return Ok(tcx.mk_const(ty::Const {
549                 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
550                     def: au.def,
551                     substs,
552                     promoted: au.promoted,
553                 }),
554                 ty: a.ty,
555             }));
556         }
557         _ => false,
558     };
559     if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
560 }
561
562 fn check_const_value_eq<R: TypeRelation<'tcx>>(
563     relation: &mut R,
564     a_val: ConstValue<'tcx>,
565     b_val: ConstValue<'tcx>,
566     // FIXME(oli-obk): these arguments should go away with valtrees
567     a: &'tcx ty::Const<'tcx>,
568     b: &'tcx ty::Const<'tcx>,
569     // FIXME(oli-obk): this should just be `bool` with valtrees
570 ) -> RelateResult<'tcx, bool> {
571     let tcx = relation.tcx();
572     Ok(match (a_val, b_val) {
573         (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => {
574             a_val == b_val
575         }
576         (ConstValue::Scalar(Scalar::Ptr(a_val)), ConstValue::Scalar(Scalar::Ptr(b_val))) => {
577             a_val == b_val
578                 || match (tcx.global_alloc(a_val.alloc_id), tcx.global_alloc(b_val.alloc_id)) {
579                     (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => {
580                         a_instance == b_instance
581                     }
582                     _ => false,
583                 }
584         }
585
586         (ConstValue::Slice { .. }, ConstValue::Slice { .. }) => {
587             get_slice_bytes(&tcx, a_val) == get_slice_bytes(&tcx, b_val)
588         }
589
590         (ConstValue::ByRef { .. }, ConstValue::ByRef { .. }) => {
591             let a_destructured = tcx.destructure_const(relation.param_env().and(a));
592             let b_destructured = tcx.destructure_const(relation.param_env().and(b));
593
594             // Both the variant and each field have to be equal.
595             if a_destructured.variant == b_destructured.variant {
596                 for (a_field, b_field) in
597                     a_destructured.fields.iter().zip(b_destructured.fields.iter())
598                 {
599                     relation.consts(a_field, b_field)?;
600                 }
601
602                 true
603             } else {
604                 false
605             }
606         }
607
608         _ => false,
609     })
610 }
611
612 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>> {
613     fn relate<R: TypeRelation<'tcx>>(
614         relation: &mut R,
615         a: Self,
616         b: Self,
617     ) -> RelateResult<'tcx, Self> {
618         let tcx = relation.tcx();
619
620         // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
621         // We need to perform this deduplication as we sometimes generate duplicate projections
622         // in `a`.
623         let mut a_v: Vec<_> = a.into_iter().collect();
624         let mut b_v: Vec<_> = b.into_iter().collect();
625         // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
626         a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
627         a_v.dedup();
628         b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
629         b_v.dedup();
630         if a_v.len() != b_v.len() {
631             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
632         }
633
634         let v = a_v.into_iter().zip(b_v.into_iter()).map(|(ep_a, ep_b)| {
635             use crate::ty::ExistentialPredicate::*;
636             match (ep_a.skip_binder(), ep_b.skip_binder()) {
637                 (Trait(a), Trait(b)) => Ok(ty::Binder::bind(Trait(
638                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
639                 ))),
640                 (Projection(a), Projection(b)) => Ok(ty::Binder::bind(Projection(
641                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
642                 ))),
643                 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
644                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
645             }
646         });
647         tcx.mk_poly_existential_predicates(v)
648     }
649 }
650
651 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
652     fn relate<R: TypeRelation<'tcx>>(
653         relation: &mut R,
654         a: ty::ClosureSubsts<'tcx>,
655         b: ty::ClosureSubsts<'tcx>,
656     ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
657         let substs = relate_substs(relation, None, a.substs, b.substs)?;
658         Ok(ty::ClosureSubsts { substs })
659     }
660 }
661
662 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
663     fn relate<R: TypeRelation<'tcx>>(
664         relation: &mut R,
665         a: ty::GeneratorSubsts<'tcx>,
666         b: ty::GeneratorSubsts<'tcx>,
667     ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
668         let substs = relate_substs(relation, None, a.substs, b.substs)?;
669         Ok(ty::GeneratorSubsts { substs })
670     }
671 }
672
673 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
674     fn relate<R: TypeRelation<'tcx>>(
675         relation: &mut R,
676         a: SubstsRef<'tcx>,
677         b: SubstsRef<'tcx>,
678     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
679         relate_substs(relation, None, a, b)
680     }
681 }
682
683 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
684     fn relate<R: TypeRelation<'tcx>>(
685         relation: &mut R,
686         a: ty::Region<'tcx>,
687         b: ty::Region<'tcx>,
688     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
689         relation.regions(a, b)
690     }
691 }
692
693 impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> {
694     fn relate<R: TypeRelation<'tcx>>(
695         relation: &mut R,
696         a: &'tcx ty::Const<'tcx>,
697         b: &'tcx ty::Const<'tcx>,
698     ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
699         relation.consts(a, b)
700     }
701 }
702
703 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
704     fn relate<R: TypeRelation<'tcx>>(
705         relation: &mut R,
706         a: ty::Binder<T>,
707         b: ty::Binder<T>,
708     ) -> RelateResult<'tcx, ty::Binder<T>> {
709         relation.binders(a, b)
710     }
711 }
712
713 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
714     fn relate<R: TypeRelation<'tcx>>(
715         relation: &mut R,
716         a: GenericArg<'tcx>,
717         b: GenericArg<'tcx>,
718     ) -> RelateResult<'tcx, GenericArg<'tcx>> {
719         match (a.unpack(), b.unpack()) {
720             (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
721                 Ok(relation.relate(a_lt, b_lt)?.into())
722             }
723             (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
724                 Ok(relation.relate(a_ty, b_ty)?.into())
725             }
726             (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
727                 Ok(relation.relate(a_ct, b_ct)?.into())
728             }
729             (GenericArgKind::Lifetime(unpacked), x) => {
730                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
731             }
732             (GenericArgKind::Type(unpacked), x) => {
733                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
734             }
735             (GenericArgKind::Const(unpacked), x) => {
736                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
737             }
738         }
739     }
740 }
741
742 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
743     fn relate<R: TypeRelation<'tcx>>(
744         relation: &mut R,
745         a: ty::TraitPredicate<'tcx>,
746         b: ty::TraitPredicate<'tcx>,
747     ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
748         Ok(ty::TraitPredicate { trait_ref: relation.relate(a.trait_ref, b.trait_ref)? })
749     }
750 }
751
752 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
753     fn relate<R: TypeRelation<'tcx>>(
754         relation: &mut R,
755         a: ty::ProjectionPredicate<'tcx>,
756         b: ty::ProjectionPredicate<'tcx>,
757     ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
758         Ok(ty::ProjectionPredicate {
759             projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
760             ty: relation.relate(a.ty, b.ty)?,
761         })
762     }
763 }
764
765 ///////////////////////////////////////////////////////////////////////////
766 // Error handling
767
768 pub fn expected_found<R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
769 where
770     R: TypeRelation<'tcx>,
771 {
772     expected_found_bool(relation.a_is_expected(), a, b)
773 }
774
775 pub fn expected_found_bool<T>(a_is_expected: bool, a: T, b: T) -> ExpectedFound<T> {
776     if a_is_expected {
777         ExpectedFound { expected: a, found: b }
778     } else {
779         ExpectedFound { expected: b, found: a }
780     }
781 }