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