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