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