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