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