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