]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/relate.rs
Rollup merge of #107100 - compiler-errors:issue-107087, r=lcnr
[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> + PartialEq + 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::AliasTy<'tcx> {
274     fn relate<R: TypeRelation<'tcx>>(
275         relation: &mut R,
276         a: ty::AliasTy<'tcx>,
277         b: ty::AliasTy<'tcx>,
278     ) -> RelateResult<'tcx, ty::AliasTy<'tcx>> {
279         if a.def_id != b.def_id {
280             Err(TypeError::ProjectionMismatched(expected_found(relation, a.def_id, b.def_id)))
281         } else {
282             let substs = relation.relate(a.substs, b.substs)?;
283             Ok(relation.tcx().mk_alias_ty(a.def_id, substs))
284         }
285     }
286 }
287
288 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
289     fn relate<R: TypeRelation<'tcx>>(
290         relation: &mut R,
291         a: ty::ExistentialProjection<'tcx>,
292         b: ty::ExistentialProjection<'tcx>,
293     ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> {
294         if a.def_id != b.def_id {
295             Err(TypeError::ProjectionMismatched(expected_found(relation, a.def_id, b.def_id)))
296         } else {
297             let term = relation.relate_with_variance(
298                 ty::Invariant,
299                 ty::VarianceDiagInfo::default(),
300                 a.term,
301                 b.term,
302             )?;
303             let substs = relation.relate_with_variance(
304                 ty::Invariant,
305                 ty::VarianceDiagInfo::default(),
306                 a.substs,
307                 b.substs,
308             )?;
309             Ok(ty::ExistentialProjection { def_id: a.def_id, substs, term })
310         }
311     }
312 }
313
314 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
315     fn relate<R: TypeRelation<'tcx>>(
316         relation: &mut R,
317         a: ty::TraitRef<'tcx>,
318         b: ty::TraitRef<'tcx>,
319     ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> {
320         // Different traits cannot be related.
321         if a.def_id != b.def_id {
322             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
323         } else {
324             let substs = relate_substs(relation, a.substs, b.substs)?;
325             Ok(relation.tcx().mk_trait_ref(a.def_id, substs))
326         }
327     }
328 }
329
330 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
331     fn relate<R: TypeRelation<'tcx>>(
332         relation: &mut R,
333         a: ty::ExistentialTraitRef<'tcx>,
334         b: ty::ExistentialTraitRef<'tcx>,
335     ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> {
336         // Different traits cannot be related.
337         if a.def_id != b.def_id {
338             Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id)))
339         } else {
340             let substs = relate_substs(relation, a.substs, b.substs)?;
341             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs })
342         }
343     }
344 }
345
346 #[derive(PartialEq, Copy, Debug, Clone, TypeFoldable, TypeVisitable)]
347 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
348
349 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
350     fn relate<R: TypeRelation<'tcx>>(
351         relation: &mut R,
352         a: GeneratorWitness<'tcx>,
353         b: GeneratorWitness<'tcx>,
354     ) -> RelateResult<'tcx, GeneratorWitness<'tcx>> {
355         assert_eq!(a.0.len(), b.0.len());
356         let tcx = relation.tcx();
357         let types = tcx.mk_type_list(iter::zip(a.0, b.0).map(|(a, b)| relation.relate(a, b)))?;
358         Ok(GeneratorWitness(types))
359     }
360 }
361
362 impl<'tcx> Relate<'tcx> for ImplSubject<'tcx> {
363     #[inline]
364     fn relate<R: TypeRelation<'tcx>>(
365         relation: &mut R,
366         a: ImplSubject<'tcx>,
367         b: ImplSubject<'tcx>,
368     ) -> RelateResult<'tcx, ImplSubject<'tcx>> {
369         match (a, b) {
370             (ImplSubject::Trait(trait_ref_a), ImplSubject::Trait(trait_ref_b)) => {
371                 let trait_ref = ty::TraitRef::relate(relation, trait_ref_a, trait_ref_b)?;
372                 Ok(ImplSubject::Trait(trait_ref))
373             }
374             (ImplSubject::Inherent(ty_a), ImplSubject::Inherent(ty_b)) => {
375                 let ty = Ty::relate(relation, ty_a, ty_b)?;
376                 Ok(ImplSubject::Inherent(ty))
377             }
378             (ImplSubject::Trait(_), ImplSubject::Inherent(_))
379             | (ImplSubject::Inherent(_), ImplSubject::Trait(_)) => {
380                 bug!("can not relate TraitRef and Ty");
381             }
382         }
383     }
384 }
385
386 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
387     #[inline]
388     fn relate<R: TypeRelation<'tcx>>(
389         relation: &mut R,
390         a: Ty<'tcx>,
391         b: Ty<'tcx>,
392     ) -> RelateResult<'tcx, Ty<'tcx>> {
393         relation.tys(a, b)
394     }
395 }
396
397 /// The main "type relation" routine. Note that this does not handle
398 /// inference artifacts, so you should filter those out before calling
399 /// it.
400 pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>(
401     relation: &mut R,
402     a: Ty<'tcx>,
403     b: Ty<'tcx>,
404 ) -> RelateResult<'tcx, Ty<'tcx>> {
405     let tcx = relation.tcx();
406     debug!("super_relate_tys: a={:?} b={:?}", a, b);
407     match (a.kind(), b.kind()) {
408         (&ty::Infer(_), _) | (_, &ty::Infer(_)) => {
409             // The caller should handle these cases!
410             bug!("var types encountered in super_relate_tys")
411         }
412
413         (ty::Bound(..), _) | (_, ty::Bound(..)) => {
414             bug!("bound types encountered in super_relate_tys")
415         }
416
417         (&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(tcx.ty_error_with_guaranteed(guar)),
418
419         (&ty::Never, _)
420         | (&ty::Char, _)
421         | (&ty::Bool, _)
422         | (&ty::Int(_), _)
423         | (&ty::Uint(_), _)
424         | (&ty::Float(_), _)
425         | (&ty::Str, _)
426             if a == b =>
427         {
428             Ok(a)
429         }
430
431         (ty::Param(a_p), ty::Param(b_p)) if a_p.index == b_p.index => Ok(a),
432
433         (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
434
435         (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => {
436             let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?;
437             Ok(tcx.mk_adt(a_def, substs))
438         }
439
440         (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)),
441
442         (&ty::Dynamic(a_obj, a_region, a_repr), &ty::Dynamic(b_obj, b_region, b_repr))
443             if a_repr == b_repr =>
444         {
445             let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| {
446                 relation.relate_with_variance(
447                     ty::Contravariant,
448                     ty::VarianceDiagInfo::default(),
449                     a_region,
450                     b_region,
451                 )
452             })?;
453             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound, a_repr))
454         }
455
456         (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _))
457             if a_id == b_id =>
458         {
459             // All Generator types with the same id represent
460             // the (anonymous) type of the same generator expression. So
461             // all of their regions should be equated.
462             let substs = relation.relate(a_substs, b_substs)?;
463             Ok(tcx.mk_generator(a_id, substs, movability))
464         }
465
466         (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => {
467             // Wrap our types with a temporary GeneratorWitness struct
468             // inside the binder so we can related them
469             let a_types = a_types.map_bound(GeneratorWitness);
470             let b_types = b_types.map_bound(GeneratorWitness);
471             // Then remove the GeneratorWitness for the result
472             let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0);
473             Ok(tcx.mk_generator_witness(types))
474         }
475
476         (&ty::GeneratorWitnessMIR(a_id, a_substs), &ty::GeneratorWitnessMIR(b_id, b_substs))
477             if a_id == b_id =>
478         {
479             // All GeneratorWitness types with the same id represent
480             // the (anonymous) type of the same generator expression. So
481             // all of their regions should be equated.
482             let substs = relation.relate(a_substs, b_substs)?;
483             Ok(tcx.mk_generator_witness_mir(a_id, substs))
484         }
485
486         (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => {
487             // All Closure types with the same id represent
488             // the (anonymous) type of the same closure expression. So
489             // all of their regions should be equated.
490             let substs = relation.relate(a_substs, b_substs)?;
491             Ok(tcx.mk_closure(a_id, &substs))
492         }
493
494         (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => {
495             let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
496             Ok(tcx.mk_ptr(mt))
497         }
498
499         (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => {
500             let r = relation.relate_with_variance(
501                 ty::Contravariant,
502                 ty::VarianceDiagInfo::default(),
503                 a_r,
504                 b_r,
505             )?;
506             let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
507             let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
508             let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?;
509             Ok(tcx.mk_ref(r, mt))
510         }
511
512         (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => {
513             let t = relation.relate(a_t, b_t)?;
514             match relation.relate(sz_a, sz_b) {
515                 Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))),
516                 Err(err) => {
517                     // Check whether the lengths are both concrete/known values,
518                     // but are unequal, for better diagnostics.
519                     //
520                     // It might seem dubious to eagerly evaluate these constants here,
521                     // we however cannot end up with errors in `Relate` during both
522                     // `type_of` and `predicates_of`. This means that evaluating the
523                     // constants should not cause cycle errors here.
524                     let sz_a = sz_a.try_eval_usize(tcx, relation.param_env());
525                     let sz_b = sz_b.try_eval_usize(tcx, relation.param_env());
526                     match (sz_a, sz_b) {
527                         (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err(
528                             TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)),
529                         ),
530                         _ => Err(err),
531                     }
532                 }
533             }
534         }
535
536         (&ty::Slice(a_t), &ty::Slice(b_t)) => {
537             let t = relation.relate(a_t, b_t)?;
538             Ok(tcx.mk_slice(t))
539         }
540
541         (&ty::Tuple(as_), &ty::Tuple(bs)) => {
542             if as_.len() == bs.len() {
543                 Ok(tcx.mk_tup(iter::zip(as_, bs).map(|(a, b)| relation.relate(a, b)))?)
544             } else if !(as_.is_empty() || bs.is_empty()) {
545                 Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len())))
546             } else {
547                 Err(TypeError::Sorts(expected_found(relation, a, b)))
548             }
549         }
550
551         (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
552             if a_def_id == b_def_id =>
553         {
554             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
555             Ok(tcx.mk_fn_def(a_def_id, substs))
556         }
557
558         (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => {
559             let fty = relation.relate(a_fty, b_fty)?;
560             Ok(tcx.mk_fn_ptr(fty))
561         }
562
563         // these two are already handled downstream in case of lazy normalization
564         (&ty::Alias(ty::Projection, a_data), &ty::Alias(ty::Projection, b_data)) => {
565             let projection_ty = relation.relate(a_data, b_data)?;
566             Ok(tcx.mk_projection(projection_ty.def_id, projection_ty.substs))
567         }
568
569         (
570             &ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, substs: a_substs, .. }),
571             &ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, substs: b_substs, .. }),
572         ) if a_def_id == b_def_id => {
573             if relation.intercrate() {
574                 // During coherence, opaque types should be treated as equal to each other, even if their generic params
575                 // differ, as they could resolve to the same hidden type, even for different generic params.
576                 relation.mark_ambiguous();
577                 Ok(a)
578             } else {
579                 let opt_variances = tcx.variances_of(a_def_id);
580                 let substs = relate_substs_with_variances(
581                     relation,
582                     a_def_id,
583                     opt_variances,
584                     a_substs,
585                     b_substs,
586                     false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle
587                 )?;
588                 Ok(tcx.mk_opaque(a_def_id, substs))
589             }
590         }
591
592         _ => Err(TypeError::Sorts(expected_found(relation, a, b))),
593     }
594 }
595
596 /// The main "const relation" routine. Note that this does not handle
597 /// inference artifacts, so you should filter those out before calling
598 /// it.
599 pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>(
600     relation: &mut R,
601     mut a: ty::Const<'tcx>,
602     mut b: ty::Const<'tcx>,
603 ) -> RelateResult<'tcx, ty::Const<'tcx>> {
604     debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b);
605     let tcx = relation.tcx();
606
607     let a_ty;
608     let b_ty;
609     if relation.tcx().features().adt_const_params {
610         a_ty = tcx.normalize_erasing_regions(relation.param_env(), a.ty());
611         b_ty = tcx.normalize_erasing_regions(relation.param_env(), b.ty());
612     } else {
613         a_ty = tcx.erase_regions(a.ty());
614         b_ty = tcx.erase_regions(b.ty());
615     }
616     if a_ty != b_ty {
617         relation.tcx().sess.delay_span_bug(
618             DUMMY_SP,
619             &format!(
620                 "cannot relate constants ({:?}, {:?}) of different types: {} != {}",
621                 a, b, a_ty, b_ty
622             ),
623         );
624     }
625
626     // HACK(const_generics): We still need to eagerly evaluate consts when
627     // relating them because during `normalize_param_env_or_error`,
628     // we may relate an evaluated constant in a obligation against
629     // an unnormalized (i.e. unevaluated) const in the param-env.
630     // FIXME(generic_const_exprs): Once we always lazily unify unevaluated constants
631     // these `eval` calls can be removed.
632     if !tcx.features().generic_const_exprs {
633         a = a.eval(tcx, relation.param_env());
634         b = b.eval(tcx, relation.param_env());
635     }
636
637     if tcx.features().generic_const_exprs {
638         a = tcx.expand_abstract_consts(a);
639         b = tcx.expand_abstract_consts(b);
640     }
641
642     // Currently, the values that can be unified are primitive types,
643     // and those that derive both `PartialEq` and `Eq`, corresponding
644     // to structural-match types.
645     let is_match = match (a.kind(), b.kind()) {
646         (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
647             // The caller should handle these cases!
648             bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b)
649         }
650
651         (ty::ConstKind::Error(_), _) => return Ok(a),
652         (_, ty::ConstKind::Error(_)) => return Ok(b),
653
654         (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) => a_p.index == b_p.index,
655         (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
656         (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
657
658         // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
659         // and is the better alternative to waiting until `generic_const_exprs` can
660         // be stabilized.
661         (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
662             assert_eq!(a.ty(), b.ty());
663             let substs = relation.relate_with_variance(
664                 ty::Variance::Invariant,
665                 ty::VarianceDiagInfo::default(),
666                 au.substs,
667                 bu.substs,
668             )?;
669             return Ok(tcx.mk_const(ty::UnevaluatedConst { def: au.def, substs }, a.ty()));
670         }
671         // Before calling relate on exprs, it is necessary to ensure that the nested consts
672         // have identical types.
673         (ty::ConstKind::Expr(ae), ty::ConstKind::Expr(be)) => {
674             let r = relation;
675
676             // FIXME(generic_const_exprs): is it possible to relate two consts which are not identical
677             // exprs? Should we care about that?
678             let expr = match (ae, be) {
679                 (Expr::Binop(a_op, al, ar), Expr::Binop(b_op, bl, br))
680                     if a_op == b_op && al.ty() == bl.ty() && ar.ty() == br.ty() =>
681                 {
682                     Expr::Binop(a_op, r.consts(al, bl)?, r.consts(ar, br)?)
683                 }
684                 (Expr::UnOp(a_op, av), Expr::UnOp(b_op, bv))
685                     if a_op == b_op && av.ty() == bv.ty() =>
686                 {
687                     Expr::UnOp(a_op, r.consts(av, bv)?)
688                 }
689                 (Expr::Cast(ak, av, at), Expr::Cast(bk, bv, bt))
690                     if ak == bk && av.ty() == bv.ty() =>
691                 {
692                     Expr::Cast(ak, r.consts(av, bv)?, r.tys(at, bt)?)
693                 }
694                 (Expr::FunctionCall(af, aa), Expr::FunctionCall(bf, ba))
695                     if aa.len() == ba.len()
696                         && af.ty() == bf.ty()
697                         && aa
698                             .iter()
699                             .zip(ba.iter())
700                             .all(|(a_arg, b_arg)| a_arg.ty() == b_arg.ty()) =>
701                 {
702                     let func = r.consts(af, bf)?;
703                     let mut related_args = Vec::with_capacity(aa.len());
704                     for (a_arg, b_arg) in aa.iter().zip(ba.iter()) {
705                         related_args.push(r.consts(a_arg, b_arg)?);
706                     }
707                     let related_args = tcx.mk_const_list(related_args.iter());
708                     Expr::FunctionCall(func, related_args)
709                 }
710                 _ => return Err(TypeError::ConstMismatch(expected_found(r, a, b))),
711             };
712             let kind = ty::ConstKind::Expr(expr);
713             return Ok(tcx.mk_const(kind, a.ty()));
714         }
715         _ => false,
716     };
717     if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) }
718 }
719
720 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
721     fn relate<R: TypeRelation<'tcx>>(
722         relation: &mut R,
723         a: Self,
724         b: Self,
725     ) -> RelateResult<'tcx, Self> {
726         let tcx = relation.tcx();
727
728         // FIXME: this is wasteful, but want to do a perf run to see how slow it is.
729         // We need to perform this deduplication as we sometimes generate duplicate projections
730         // in `a`.
731         let mut a_v: Vec<_> = a.into_iter().collect();
732         let mut b_v: Vec<_> = b.into_iter().collect();
733         // `skip_binder` here is okay because `stable_cmp` doesn't look at binders
734         a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
735         a_v.dedup();
736         b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
737         b_v.dedup();
738         if a_v.len() != b_v.len() {
739             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
740         }
741
742         let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| {
743             use crate::ty::ExistentialPredicate::*;
744             match (ep_a.skip_binder(), ep_b.skip_binder()) {
745                 (Trait(a), Trait(b)) => Ok(ep_a
746                     .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))),
747                 (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection(
748                     relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(),
749                 ))),
750                 (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))),
751                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))),
752             }
753         });
754         tcx.mk_poly_existential_predicates(v)
755     }
756 }
757
758 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
759     fn relate<R: TypeRelation<'tcx>>(
760         relation: &mut R,
761         a: ty::ClosureSubsts<'tcx>,
762         b: ty::ClosureSubsts<'tcx>,
763     ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> {
764         let substs = relate_substs(relation, a.substs, b.substs)?;
765         Ok(ty::ClosureSubsts { substs })
766     }
767 }
768
769 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
770     fn relate<R: TypeRelation<'tcx>>(
771         relation: &mut R,
772         a: ty::GeneratorSubsts<'tcx>,
773         b: ty::GeneratorSubsts<'tcx>,
774     ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> {
775         let substs = relate_substs(relation, a.substs, b.substs)?;
776         Ok(ty::GeneratorSubsts { substs })
777     }
778 }
779
780 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
781     fn relate<R: TypeRelation<'tcx>>(
782         relation: &mut R,
783         a: SubstsRef<'tcx>,
784         b: SubstsRef<'tcx>,
785     ) -> RelateResult<'tcx, SubstsRef<'tcx>> {
786         relate_substs(relation, a, b)
787     }
788 }
789
790 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
791     fn relate<R: TypeRelation<'tcx>>(
792         relation: &mut R,
793         a: ty::Region<'tcx>,
794         b: ty::Region<'tcx>,
795     ) -> RelateResult<'tcx, ty::Region<'tcx>> {
796         relation.regions(a, b)
797     }
798 }
799
800 impl<'tcx> Relate<'tcx> for ty::Const<'tcx> {
801     fn relate<R: TypeRelation<'tcx>>(
802         relation: &mut R,
803         a: ty::Const<'tcx>,
804         b: ty::Const<'tcx>,
805     ) -> RelateResult<'tcx, ty::Const<'tcx>> {
806         relation.consts(a, b)
807     }
808 }
809
810 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> {
811     fn relate<R: TypeRelation<'tcx>>(
812         relation: &mut R,
813         a: ty::Binder<'tcx, T>,
814         b: ty::Binder<'tcx, T>,
815     ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> {
816         relation.binders(a, b)
817     }
818 }
819
820 impl<'tcx> Relate<'tcx> for GenericArg<'tcx> {
821     fn relate<R: TypeRelation<'tcx>>(
822         relation: &mut R,
823         a: GenericArg<'tcx>,
824         b: GenericArg<'tcx>,
825     ) -> RelateResult<'tcx, GenericArg<'tcx>> {
826         match (a.unpack(), b.unpack()) {
827             (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => {
828                 Ok(relation.relate(a_lt, b_lt)?.into())
829             }
830             (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => {
831                 Ok(relation.relate(a_ty, b_ty)?.into())
832             }
833             (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => {
834                 Ok(relation.relate(a_ct, b_ct)?.into())
835             }
836             (GenericArgKind::Lifetime(unpacked), x) => {
837                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
838             }
839             (GenericArgKind::Type(unpacked), x) => {
840                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
841             }
842             (GenericArgKind::Const(unpacked), x) => {
843                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
844             }
845         }
846     }
847 }
848
849 impl<'tcx> Relate<'tcx> for ty::ImplPolarity {
850     fn relate<R: TypeRelation<'tcx>>(
851         relation: &mut R,
852         a: ty::ImplPolarity,
853         b: ty::ImplPolarity,
854     ) -> RelateResult<'tcx, ty::ImplPolarity> {
855         if a != b {
856             Err(TypeError::PolarityMismatch(expected_found(relation, a, b)))
857         } else {
858             Ok(a)
859         }
860     }
861 }
862
863 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
864     fn relate<R: TypeRelation<'tcx>>(
865         relation: &mut R,
866         a: ty::TraitPredicate<'tcx>,
867         b: ty::TraitPredicate<'tcx>,
868     ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> {
869         Ok(ty::TraitPredicate {
870             trait_ref: relation.relate(a.trait_ref, b.trait_ref)?,
871             constness: relation.relate(a.constness, b.constness)?,
872             polarity: relation.relate(a.polarity, b.polarity)?,
873         })
874     }
875 }
876
877 impl<'tcx> Relate<'tcx> for Term<'tcx> {
878     fn relate<R: TypeRelation<'tcx>>(
879         relation: &mut R,
880         a: Self,
881         b: Self,
882     ) -> RelateResult<'tcx, Self> {
883         Ok(match (a.unpack(), b.unpack()) {
884             (TermKind::Ty(a), TermKind::Ty(b)) => relation.relate(a, b)?.into(),
885             (TermKind::Const(a), TermKind::Const(b)) => relation.relate(a, b)?.into(),
886             _ => return Err(TypeError::Mismatch),
887         })
888     }
889 }
890
891 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
892     fn relate<R: TypeRelation<'tcx>>(
893         relation: &mut R,
894         a: ty::ProjectionPredicate<'tcx>,
895         b: ty::ProjectionPredicate<'tcx>,
896     ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
897         Ok(ty::ProjectionPredicate {
898             projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
899             term: relation.relate(a.term, b.term)?,
900         })
901     }
902 }
903
904 ///////////////////////////////////////////////////////////////////////////
905 // Error handling
906
907 pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound<T>
908 where
909     R: TypeRelation<'tcx>,
910 {
911     ExpectedFound::new(relation.a_is_expected(), a, b)
912 }