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