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