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