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