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