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