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