]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/relate.rs
Auto merge of #58709 - kornelski:book, r=QuietMisdreavus
[rust.git] / src / librustc / 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::hir::def_id::DefId;
8 use crate::ty::subst::{Kind, UnpackedKind, SubstsRef};
9 use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
10 use crate::ty::error::{ExpectedFound, TypeError};
11 use crate::mir::interpret::GlobalId;
12 use crate::util::common::ErrorReported;
13 use syntax_pos::DUMMY_SP;
14 use std::rc::Rc;
15 use std::iter;
16 use rustc_target::spec::abi;
17 use crate::hir as ast;
18 use crate::traits;
19
20 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
21
22 #[derive(Clone, Debug)]
23 pub enum Cause {
24     ExistentialRegionBound, // relating an existential region bound
25 }
26
27 pub trait TypeRelation<'a, 'gcx: 'a+'tcx, 'tcx: 'a> : Sized {
28     fn tcx(&self) -> TyCtxt<'a, 'gcx, '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     fn with_cause<F,R>(&mut self, _cause: Cause, f: F) -> R
38         where F: FnOnce(&mut Self) -> R
39     {
40         f(self)
41     }
42
43     /// Generic relation routine suitable for most anything.
44     fn relate<T: Relate<'tcx>>(&mut self, a: &T, b: &T) -> RelateResult<'tcx, T> {
45         Relate::relate(self, a, b)
46     }
47
48     /// Relate the two substitutions for the given item. The default
49     /// is to look up the variance for the item and proceed
50     /// accordingly.
51     fn relate_item_substs(&mut self,
52                           item_def_id: DefId,
53                           a_subst: SubstsRef<'tcx>,
54                           b_subst: SubstsRef<'tcx>)
55                           -> RelateResult<'tcx, SubstsRef<'tcx>>
56     {
57         debug!("relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
58                item_def_id,
59                a_subst,
60                b_subst);
61
62         let opt_variances = self.tcx().variances_of(item_def_id);
63         relate_substs(self, Some(&opt_variances), a_subst, b_subst)
64     }
65
66     /// Switch variance for the purpose of relating `a` and `b`.
67     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
68                                              variance: ty::Variance,
69                                              a: &T,
70                                              b: &T)
71                                              -> RelateResult<'tcx, T>;
72
73     // Overrideable relations. You shouldn't typically call these
74     // directly, instead call `relate()`, which in turn calls
75     // these. This is both more uniform but also allows us to add
76     // additional hooks for other types in the future if needed
77     // without making older code, which called `relate`, obsolete.
78
79     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>)
80            -> RelateResult<'tcx, Ty<'tcx>>;
81
82     fn regions(&mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>)
83                -> RelateResult<'tcx, ty::Region<'tcx>>;
84
85     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
86                   -> RelateResult<'tcx, ty::Binder<T>>
87         where T: Relate<'tcx>;
88 }
89
90 pub trait Relate<'tcx>: TypeFoldable<'tcx> {
91     fn relate<'a, 'gcx, R>(relation: &mut R, a: &Self, b: &Self)
92                            -> RelateResult<'tcx, Self>
93         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a;
94 }
95
96 ///////////////////////////////////////////////////////////////////////////
97 // Relate impls
98
99 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
100     fn relate<'a, 'gcx, R>(relation: &mut R,
101                            a: &ty::TypeAndMut<'tcx>,
102                            b: &ty::TypeAndMut<'tcx>)
103                            -> RelateResult<'tcx, ty::TypeAndMut<'tcx>>
104         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
105     {
106         debug!("{}.mts({:?}, {:?})",
107                relation.tag(),
108                a,
109                b);
110         if a.mutbl != b.mutbl {
111             Err(TypeError::Mutability)
112         } else {
113             let mutbl = a.mutbl;
114             let variance = match mutbl {
115                 ast::Mutability::MutImmutable => ty::Covariant,
116                 ast::Mutability::MutMutable => ty::Invariant,
117             };
118             let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
119             Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
120         }
121     }
122 }
123
124 pub fn relate_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
125                                         variances: Option<&Vec<ty::Variance>>,
126                                         a_subst: SubstsRef<'tcx>,
127                                         b_subst: SubstsRef<'tcx>)
128                                         -> RelateResult<'tcx, SubstsRef<'tcx>>
129     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
130 {
131     let tcx = relation.tcx();
132
133     let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
134         let variance = variances.map_or(ty::Invariant, |v| v[i]);
135         relation.relate_with_variance(variance, a, b)
136     });
137
138     Ok(tcx.mk_substs(params)?)
139 }
140
141 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
142     fn relate<'a, 'gcx, R>(relation: &mut R,
143                            a: &ty::FnSig<'tcx>,
144                            b: &ty::FnSig<'tcx>)
145                            -> RelateResult<'tcx, ty::FnSig<'tcx>>
146         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
147     {
148         let tcx = relation.tcx();
149
150         if a.variadic != b.variadic {
151             return Err(TypeError::VariadicMismatch(
152                 expected_found(relation, &a.variadic, &b.variadic)));
153         }
154         let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
155         let abi = relation.relate(&a.abi, &b.abi)?;
156
157         if a.inputs().len() != b.inputs().len() {
158             return Err(TypeError::ArgCount);
159         }
160
161         let inputs_and_output = a.inputs().iter().cloned()
162             .zip(b.inputs().iter().cloned())
163             .map(|x| (x, false))
164             .chain(iter::once(((a.output(), b.output()), true)))
165             .map(|((a, b), is_output)| {
166                 if is_output {
167                     relation.relate(&a, &b)
168                 } else {
169                     relation.relate_with_variance(ty::Contravariant, &a, &b)
170                 }
171             });
172         Ok(ty::FnSig {
173             inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
174             variadic: a.variadic,
175             unsafety,
176             abi,
177         })
178     }
179 }
180
181 impl<'tcx> Relate<'tcx> for ast::Unsafety {
182     fn relate<'a, 'gcx, R>(relation: &mut R,
183                            a: &ast::Unsafety,
184                            b: &ast::Unsafety)
185                            -> RelateResult<'tcx, ast::Unsafety>
186         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
187     {
188         if a != b {
189             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
190         } else {
191             Ok(*a)
192         }
193     }
194 }
195
196 impl<'tcx> Relate<'tcx> for abi::Abi {
197     fn relate<'a, 'gcx, R>(relation: &mut R,
198                            a: &abi::Abi,
199                            b: &abi::Abi)
200                            -> RelateResult<'tcx, abi::Abi>
201         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
202     {
203         if a == b {
204             Ok(*a)
205         } else {
206             Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
207         }
208     }
209 }
210
211 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
212     fn relate<'a, 'gcx, R>(relation: &mut R,
213                            a: &ty::ProjectionTy<'tcx>,
214                            b: &ty::ProjectionTy<'tcx>)
215                            -> RelateResult<'tcx, ty::ProjectionTy<'tcx>>
216         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
217     {
218         if a.item_def_id != b.item_def_id {
219             Err(TypeError::ProjectionMismatched(
220                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
221         } else {
222             let substs = relation.relate(&a.substs, &b.substs)?;
223             Ok(ty::ProjectionTy {
224                 item_def_id: a.item_def_id,
225                 substs: &substs,
226             })
227         }
228     }
229 }
230
231 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
232     fn relate<'a, 'gcx, R>(relation: &mut R,
233                            a: &ty::ExistentialProjection<'tcx>,
234                            b: &ty::ExistentialProjection<'tcx>)
235                            -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>>
236         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
237     {
238         if a.item_def_id != b.item_def_id {
239             Err(TypeError::ProjectionMismatched(
240                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
241         } else {
242             let ty = relation.relate(&a.ty, &b.ty)?;
243             let substs = relation.relate(&a.substs, &b.substs)?;
244             Ok(ty::ExistentialProjection {
245                 item_def_id: a.item_def_id,
246                 substs,
247                 ty,
248             })
249         }
250     }
251 }
252
253 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
254     fn relate<'a, 'gcx, R>(relation: &mut R,
255                            a: &Vec<ty::PolyExistentialProjection<'tcx>>,
256                            b: &Vec<ty::PolyExistentialProjection<'tcx>>)
257                            -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>>
258         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
259     {
260         // To be compatible, `a` and `b` must be for precisely the
261         // same set of traits and item names. We always require that
262         // projection bounds lists are sorted by trait-def-id and item-name,
263         // so we can just iterate through the lists pairwise, so long as they are the
264         // same length.
265         if a.len() != b.len() {
266             Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
267         } else {
268             a.iter()
269              .zip(b)
270              .map(|(a, b)| relation.relate(a, b))
271              .collect()
272         }
273     }
274 }
275
276 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
277     fn relate<'a, 'gcx, R>(relation: &mut R,
278                            a: &ty::TraitRef<'tcx>,
279                            b: &ty::TraitRef<'tcx>)
280                            -> RelateResult<'tcx, ty::TraitRef<'tcx>>
281         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
282     {
283         // Different traits cannot be related
284         if a.def_id != b.def_id {
285             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
286         } else {
287             let substs = relate_substs(relation, None, a.substs, b.substs)?;
288             Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
289         }
290     }
291 }
292
293 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
294     fn relate<'a, 'gcx, R>(relation: &mut R,
295                            a: &ty::ExistentialTraitRef<'tcx>,
296                            b: &ty::ExistentialTraitRef<'tcx>)
297                            -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>>
298         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
299     {
300         // Different traits cannot be related
301         if a.def_id != b.def_id {
302             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
303         } else {
304             let substs = relate_substs(relation, None, a.substs, b.substs)?;
305             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
306         }
307     }
308 }
309
310 #[derive(Debug, Clone)]
311 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
312
313 TupleStructTypeFoldableImpl! {
314     impl<'tcx> TypeFoldable<'tcx> for GeneratorWitness<'tcx> {
315         a
316     }
317 }
318
319 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
320     fn relate<'a, 'gcx, R>(relation: &mut R,
321                            a: &GeneratorWitness<'tcx>,
322                            b: &GeneratorWitness<'tcx>)
323                            -> RelateResult<'tcx, GeneratorWitness<'tcx>>
324         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
325     {
326         assert_eq!(a.0.len(), b.0.len());
327         let tcx = relation.tcx();
328         let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
329         Ok(GeneratorWitness(types))
330     }
331 }
332
333 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
334     fn relate<'a, 'gcx, R>(relation: &mut R,
335                            a: &Ty<'tcx>,
336                            b: &Ty<'tcx>)
337                            -> RelateResult<'tcx, Ty<'tcx>>
338         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
339     {
340         relation.tys(a, b)
341     }
342 }
343
344 /// The main "type relation" routine. Note that this does not handle
345 /// inference artifacts, so you should filter those out before calling
346 /// it.
347 pub fn super_relate_tys<'a, 'gcx, 'tcx, R>(relation: &mut R,
348                                            a: Ty<'tcx>,
349                                            b: Ty<'tcx>)
350                                            -> RelateResult<'tcx, Ty<'tcx>>
351     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
352 {
353     let tcx = relation.tcx();
354     let a_sty = &a.sty;
355     let b_sty = &b.sty;
356     debug!("super_relate_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
357     match (a_sty, b_sty) {
358         (&ty::Infer(_), _) |
359         (_, &ty::Infer(_)) =>
360         {
361             // The caller should handle these cases!
362             bug!("var types encountered in super_relate_tys")
363         }
364
365         (ty::Bound(..), _) | (_, ty::Bound(..)) => {
366             bug!("bound types encountered in super_relate_tys")
367         }
368
369         (&ty::Error, _) | (_, &ty::Error) =>
370         {
371             Ok(tcx.types.err)
372         }
373
374         (&ty::Never, _) |
375         (&ty::Char, _) |
376         (&ty::Bool, _) |
377         (&ty::Int(_), _) |
378         (&ty::Uint(_), _) |
379         (&ty::Float(_), _) |
380         (&ty::Str, _)
381             if a == b =>
382         {
383             Ok(a)
384         }
385
386         (&ty::Param(ref a_p), &ty::Param(ref b_p))
387             if a_p.idx == b_p.idx =>
388         {
389             Ok(a)
390         }
391
392         (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => {
393             Ok(a)
394         }
395
396         (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs))
397             if a_def == b_def =>
398         {
399             let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
400             Ok(tcx.mk_adt(a_def, substs))
401         }
402
403         (&ty::Foreign(a_id), &ty::Foreign(b_id))
404             if a_id == b_id =>
405         {
406             Ok(tcx.mk_foreign(a_id))
407         }
408
409         (&ty::Dynamic(ref a_obj, ref a_region), &ty::Dynamic(ref b_obj, ref b_region)) => {
410             let region_bound = relation.with_cause(Cause::ExistentialRegionBound,
411                                                        |relation| {
412                                                            relation.relate_with_variance(
413                                                                ty::Contravariant,
414                                                                a_region,
415                                                                b_region)
416                                                        })?;
417             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
418         }
419
420         (&ty::Generator(a_id, a_substs, movability),
421          &ty::Generator(b_id, b_substs, _))
422             if a_id == b_id =>
423         {
424             // All Generator types with the same id represent
425             // the (anonymous) type of the same generator expression. So
426             // all of their regions should be equated.
427             let substs = relation.relate(&a_substs, &b_substs)?;
428             Ok(tcx.mk_generator(a_id, substs, movability))
429         }
430
431         (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) =>
432         {
433             // Wrap our types with a temporary GeneratorWitness struct
434             // inside the binder so we can related them
435             let a_types = a_types.map_bound(GeneratorWitness);
436             let b_types = b_types.map_bound(GeneratorWitness);
437             // Then remove the GeneratorWitness for the result
438             let types = relation.relate(&a_types, &b_types)?.map_bound(|witness| witness.0);
439             Ok(tcx.mk_generator_witness(types))
440         }
441
442         (&ty::Closure(a_id, a_substs),
443          &ty::Closure(b_id, b_substs))
444             if a_id == b_id =>
445         {
446             // All Closure types with the same id represent
447             // the (anonymous) type of the same closure expression. So
448             // all of their regions should be equated.
449             let substs = relation.relate(&a_substs, &b_substs)?;
450             Ok(tcx.mk_closure(a_id, substs))
451         }
452
453         (&ty::RawPtr(ref a_mt), &ty::RawPtr(ref b_mt)) =>
454         {
455             let mt = relation.relate(a_mt, b_mt)?;
456             Ok(tcx.mk_ptr(mt))
457         }
458
459         (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) =>
460         {
461             let r = relation.relate_with_variance(ty::Contravariant, &a_r, &b_r)?;
462             let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl };
463             let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl };
464             let mt = relation.relate(&a_mt, &b_mt)?;
465             Ok(tcx.mk_ref(r, mt))
466         }
467
468         (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) =>
469         {
470             let t = relation.relate(&a_t, &b_t)?;
471             let to_u64 = |x: ty::LazyConst<'tcx>| -> Result<u64, ErrorReported> {
472                 match x {
473                     ty::LazyConst::Unevaluated(def_id, substs) => {
474                         // FIXME(eddyb) get the right param_env.
475                         let param_env = ty::ParamEnv::empty();
476                         if let Some(substs) = tcx.lift_to_global(&substs) {
477                             let instance = ty::Instance::resolve(
478                                 tcx.global_tcx(),
479                                 param_env,
480                                 def_id,
481                                 substs,
482                             );
483                             if let Some(instance) = instance {
484                                 let cid = GlobalId {
485                                     instance,
486                                     promoted: None
487                                 };
488                                 if let Some(s) = tcx.const_eval(param_env.and(cid))
489                                                     .ok()
490                                                     .map(|c| c.unwrap_usize(tcx)) {
491                                     return Ok(s)
492                                 }
493                             }
494                         }
495                         tcx.sess.delay_span_bug(tcx.def_span(def_id),
496                             "array length could not be evaluated");
497                         Err(ErrorReported)
498                     }
499                     ty::LazyConst::Evaluated(c) => c.assert_usize(tcx).ok_or_else(|| {
500                         tcx.sess.delay_span_bug(DUMMY_SP,
501                             "array length could not be evaluated");
502                         ErrorReported
503                     })
504                 }
505             };
506             match (to_u64(*sz_a), to_u64(*sz_b)) {
507                 (Ok(sz_a_u64), Ok(sz_b_u64)) => {
508                     if sz_a_u64 == sz_b_u64 {
509                         Ok(tcx.mk_ty(ty::Array(t, sz_a)))
510                     } else {
511                         Err(TypeError::FixedArraySize(
512                             expected_found(relation, &sz_a_u64, &sz_b_u64)))
513                     }
514                 }
515                 // We reported an error or will ICE, so we can return Error.
516                 (Err(ErrorReported), _) | (_, Err(ErrorReported)) => {
517                     Ok(tcx.types.err)
518                 }
519             }
520         }
521
522         (&ty::Slice(a_t), &ty::Slice(b_t)) =>
523         {
524             let t = relation.relate(&a_t, &b_t)?;
525             Ok(tcx.mk_slice(t))
526         }
527
528         (&ty::Tuple(as_), &ty::Tuple(bs)) =>
529         {
530             if as_.len() == bs.len() {
531                 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| relation.relate(a, b)))?)
532             } else if !(as_.is_empty() || bs.is_empty()) {
533                 Err(TypeError::TupleSize(
534                     expected_found(relation, &as_.len(), &bs.len())))
535             } else {
536                 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
537             }
538         }
539
540         (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
541             if a_def_id == b_def_id =>
542         {
543             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
544             Ok(tcx.mk_fn_def(a_def_id, substs))
545         }
546
547         (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) =>
548         {
549             let fty = relation.relate(&a_fty, &b_fty)?;
550             Ok(tcx.mk_fn_ptr(fty))
551         }
552
553         (ty::UnnormalizedProjection(a_data), ty::UnnormalizedProjection(b_data)) => {
554             let projection_ty = relation.relate(a_data, b_data)?;
555             Ok(tcx.mk_ty(ty::UnnormalizedProjection(projection_ty)))
556         }
557
558         // these two are already handled downstream in case of lazy normalization
559         (ty::Projection(a_data), ty::Projection(b_data)) => {
560             let projection_ty = relation.relate(a_data, b_data)?;
561             Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
562         }
563
564         (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
565             if a_def_id == b_def_id =>
566         {
567             let substs = relate_substs(relation, None, a_substs, b_substs)?;
568             Ok(tcx.mk_opaque(a_def_id, substs))
569         }
570
571         _ =>
572         {
573             Err(TypeError::Sorts(expected_found(relation, &a, &b)))
574         }
575     }
576 }
577
578 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::ExistentialPredicate<'tcx>> {
579     fn relate<'a, 'gcx, R>(relation: &mut R,
580                            a: &Self,
581                            b: &Self)
582         -> RelateResult<'tcx, Self>
583             where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a {
584
585         if a.len() != b.len() {
586             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
587         }
588
589         let tcx = relation.tcx();
590         let v = a.iter().zip(b.iter()).map(|(ep_a, ep_b)| {
591             use crate::ty::ExistentialPredicate::*;
592             match (*ep_a, *ep_b) {
593                 (Trait(ref a), Trait(ref b)) => Ok(Trait(relation.relate(a, b)?)),
594                 (Projection(ref a), Projection(ref b)) => Ok(Projection(relation.relate(a, b)?)),
595                 (AutoTrait(ref a), AutoTrait(ref b)) if a == b => Ok(AutoTrait(*a)),
596                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)))
597             }
598         });
599         Ok(tcx.mk_existential_predicates(v)?)
600     }
601 }
602
603 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
604     fn relate<'a, 'gcx, R>(relation: &mut R,
605                            a: &ty::ClosureSubsts<'tcx>,
606                            b: &ty::ClosureSubsts<'tcx>)
607                            -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
608         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
609     {
610         let substs = relate_substs(relation, None, a.substs, b.substs)?;
611         Ok(ty::ClosureSubsts { substs })
612     }
613 }
614
615 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
616     fn relate<'a, 'gcx, R>(relation: &mut R,
617                            a: &ty::GeneratorSubsts<'tcx>,
618                            b: &ty::GeneratorSubsts<'tcx>)
619                            -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>>
620         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
621     {
622         let substs = relate_substs(relation, None, a.substs, b.substs)?;
623         Ok(ty::GeneratorSubsts { substs })
624     }
625 }
626
627 impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> {
628     fn relate<'a, 'gcx, R>(relation: &mut R,
629                            a: &SubstsRef<'tcx>,
630                            b: &SubstsRef<'tcx>)
631                            -> RelateResult<'tcx, SubstsRef<'tcx>>
632         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
633     {
634         relate_substs(relation, None, a, b)
635     }
636 }
637
638 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
639     fn relate<'a, 'gcx, R>(relation: &mut R,
640                            a: &ty::Region<'tcx>,
641                            b: &ty::Region<'tcx>)
642                            -> RelateResult<'tcx, ty::Region<'tcx>>
643         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
644     {
645         relation.regions(*a, *b)
646     }
647 }
648
649 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
650     fn relate<'a, 'gcx, R>(relation: &mut R,
651                            a: &ty::Binder<T>,
652                            b: &ty::Binder<T>)
653                            -> RelateResult<'tcx, ty::Binder<T>>
654         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
655     {
656         relation.binders(a, b)
657     }
658 }
659
660 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
661     fn relate<'a, 'gcx, R>(relation: &mut R,
662                            a: &Rc<T>,
663                            b: &Rc<T>)
664                            -> RelateResult<'tcx, Rc<T>>
665         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
666     {
667         let a: &T = a;
668         let b: &T = b;
669         Ok(Rc::new(relation.relate(a, b)?))
670     }
671 }
672
673 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
674     fn relate<'a, 'gcx, R>(relation: &mut R,
675                            a: &Box<T>,
676                            b: &Box<T>)
677                            -> RelateResult<'tcx, Box<T>>
678         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
679     {
680         let a: &T = a;
681         let b: &T = b;
682         Ok(Box::new(relation.relate(a, b)?))
683     }
684 }
685
686 impl<'tcx> Relate<'tcx> for Kind<'tcx> {
687     fn relate<'a, 'gcx, R>(
688         relation: &mut R,
689         a: &Kind<'tcx>,
690         b: &Kind<'tcx>
691     ) -> RelateResult<'tcx, Kind<'tcx>>
692     where
693         R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a,
694     {
695         match (a.unpack(), b.unpack()) {
696             (UnpackedKind::Lifetime(a_lt), UnpackedKind::Lifetime(b_lt)) => {
697                 Ok(relation.relate(&a_lt, &b_lt)?.into())
698             }
699             (UnpackedKind::Type(a_ty), UnpackedKind::Type(b_ty)) => {
700                 Ok(relation.relate(&a_ty, &b_ty)?.into())
701             }
702             (UnpackedKind::Lifetime(unpacked), x) => {
703                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
704             }
705             (UnpackedKind::Type(unpacked), x) => {
706                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
707             }
708         }
709     }
710 }
711
712 impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> {
713     fn relate<'a, 'gcx, R>(
714         relation: &mut R,
715         a: &ty::TraitPredicate<'tcx>,
716         b: &ty::TraitPredicate<'tcx>
717     ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>>
718         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
719     {
720         Ok(ty::TraitPredicate {
721             trait_ref: relation.relate(&a.trait_ref, &b.trait_ref)?,
722         })
723     }
724 }
725
726 impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
727     fn relate<'a, 'gcx, R>(
728         relation: &mut R,
729         a: &ty::ProjectionPredicate<'tcx>,
730         b: &ty::ProjectionPredicate<'tcx>,
731     ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>>
732         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
733     {
734         Ok(ty::ProjectionPredicate {
735             projection_ty: relation.relate(&a.projection_ty, &b.projection_ty)?,
736             ty: relation.relate(&a.ty, &b.ty)?,
737         })
738     }
739 }
740
741 impl<'tcx> Relate<'tcx> for traits::WhereClause<'tcx> {
742     fn relate<'a, 'gcx, R>(
743         relation: &mut R,
744         a: &traits::WhereClause<'tcx>,
745         b: &traits::WhereClause<'tcx>
746     ) -> RelateResult<'tcx, traits::WhereClause<'tcx>>
747         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
748     {
749         use crate::traits::WhereClause::*;
750         match (a, b) {
751             (Implemented(a_pred), Implemented(b_pred)) => {
752                 Ok(Implemented(relation.relate(a_pred, b_pred)?))
753             }
754
755             (ProjectionEq(a_pred), ProjectionEq(b_pred)) => {
756                 Ok(ProjectionEq(relation.relate(a_pred, b_pred)?))
757             }
758
759             (RegionOutlives(a_pred), RegionOutlives(b_pred)) => {
760                 Ok(RegionOutlives(ty::OutlivesPredicate(
761                     relation.relate(&a_pred.0, &b_pred.0)?,
762                     relation.relate(&a_pred.1, &b_pred.1)?,
763                 )))
764             }
765
766             (TypeOutlives(a_pred), TypeOutlives(b_pred)) => {
767                 Ok(TypeOutlives(ty::OutlivesPredicate(
768                     relation.relate(&a_pred.0, &b_pred.0)?,
769                     relation.relate(&a_pred.1, &b_pred.1)?,
770                 )))
771             }
772
773             _ =>  Err(TypeError::Mismatch),
774         }
775     }
776 }
777
778 impl<'tcx> Relate<'tcx> for traits::WellFormed<'tcx> {
779     fn relate<'a, 'gcx, R>(
780         relation: &mut R,
781         a: &traits::WellFormed<'tcx>,
782         b: &traits::WellFormed<'tcx>
783     ) -> RelateResult<'tcx, traits::WellFormed<'tcx>>
784         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
785     {
786         use crate::traits::WellFormed::*;
787         match (a, b) {
788             (Trait(a_pred), Trait(b_pred)) => Ok(Trait(relation.relate(a_pred, b_pred)?)),
789             (Ty(a_ty), Ty(b_ty)) => Ok(Ty(relation.relate(a_ty, b_ty)?)),
790             _ =>  Err(TypeError::Mismatch),
791         }
792     }
793 }
794
795 impl<'tcx> Relate<'tcx> for traits::FromEnv<'tcx> {
796     fn relate<'a, 'gcx, R>(
797         relation: &mut R,
798         a: &traits::FromEnv<'tcx>,
799         b: &traits::FromEnv<'tcx>
800     ) -> RelateResult<'tcx, traits::FromEnv<'tcx>>
801         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
802     {
803         use crate::traits::FromEnv::*;
804         match (a, b) {
805             (Trait(a_pred), Trait(b_pred)) => Ok(Trait(relation.relate(a_pred, b_pred)?)),
806             (Ty(a_ty), Ty(b_ty)) => Ok(Ty(relation.relate(a_ty, b_ty)?)),
807             _ =>  Err(TypeError::Mismatch),
808         }
809     }
810 }
811
812 impl<'tcx> Relate<'tcx> for traits::DomainGoal<'tcx> {
813     fn relate<'a, 'gcx, R>(
814         relation: &mut R,
815         a: &traits::DomainGoal<'tcx>,
816         b: &traits::DomainGoal<'tcx>
817     ) -> RelateResult<'tcx, traits::DomainGoal<'tcx>>
818         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
819     {
820         use crate::traits::DomainGoal::*;
821         match (a, b) {
822             (Holds(a_wc), Holds(b_wc)) => Ok(Holds(relation.relate(a_wc, b_wc)?)),
823             (WellFormed(a_wf), WellFormed(b_wf)) => Ok(WellFormed(relation.relate(a_wf, b_wf)?)),
824             (FromEnv(a_fe), FromEnv(b_fe)) => Ok(FromEnv(relation.relate(a_fe, b_fe)?)),
825
826             (Normalize(a_pred), Normalize(b_pred)) => {
827                 Ok(Normalize(relation.relate(a_pred, b_pred)?))
828             }
829
830             _ =>  Err(TypeError::Mismatch),
831         }
832     }
833 }
834
835 impl<'tcx> Relate<'tcx> for traits::Goal<'tcx> {
836     fn relate<'a, 'gcx, R>(
837         relation: &mut R,
838         a: &traits::Goal<'tcx>,
839         b: &traits::Goal<'tcx>
840     ) -> RelateResult<'tcx, traits::Goal<'tcx>>
841         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
842     {
843         use crate::traits::GoalKind::*;
844         match (a, b) {
845             (Implies(a_clauses, a_goal), Implies(b_clauses, b_goal)) => {
846                 let clauses = relation.relate(a_clauses, b_clauses)?;
847                 let goal = relation.relate(a_goal, b_goal)?;
848                 Ok(relation.tcx().mk_goal(Implies(clauses, goal)))
849             }
850
851             (And(a_left, a_right), And(b_left, b_right)) => {
852                 let left = relation.relate(a_left, b_left)?;
853                 let right = relation.relate(a_right, b_right)?;
854                 Ok(relation.tcx().mk_goal(And(left, right)))
855             }
856
857             (Not(a_goal), Not(b_goal)) => {
858                 let goal = relation.relate(a_goal, b_goal)?;
859                 Ok(relation.tcx().mk_goal(Not(goal)))
860             }
861
862             (DomainGoal(a_goal), DomainGoal(b_goal)) => {
863                 let goal = relation.relate(a_goal, b_goal)?;
864                 Ok(relation.tcx().mk_goal(DomainGoal(goal)))
865             }
866
867             (Quantified(a_qkind, a_goal), Quantified(b_qkind, b_goal))
868                 if a_qkind == b_qkind =>
869             {
870                 let goal = relation.relate(a_goal, b_goal)?;
871                 Ok(relation.tcx().mk_goal(Quantified(*a_qkind, goal)))
872             }
873
874             (CannotProve, CannotProve) => Ok(*a),
875
876             _ => Err(TypeError::Mismatch),
877         }
878     }
879 }
880
881 impl<'tcx> Relate<'tcx> for traits::Goals<'tcx> {
882     fn relate<'a, 'gcx, R>(
883         relation: &mut R,
884         a: &traits::Goals<'tcx>,
885         b: &traits::Goals<'tcx>
886     ) -> RelateResult<'tcx, traits::Goals<'tcx>>
887         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
888     {
889         if a.len() != b.len() {
890             return Err(TypeError::Mismatch);
891         }
892
893         let tcx = relation.tcx();
894         let goals = a.iter().zip(b.iter()).map(|(a, b)| relation.relate(a, b));
895         Ok(tcx.mk_goals(goals)?)
896     }
897 }
898
899 impl<'tcx> Relate<'tcx> for traits::Clause<'tcx> {
900     fn relate<'a, 'gcx, R>(
901         relation: &mut R,
902         a: &traits::Clause<'tcx>,
903         b: &traits::Clause<'tcx>
904     ) -> RelateResult<'tcx, traits::Clause<'tcx>>
905         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
906     {
907         use crate::traits::Clause::*;
908         match (a, b) {
909             (Implies(a_clause), Implies(b_clause)) => {
910                 let clause = relation.relate(a_clause, b_clause)?;
911                 Ok(Implies(clause))
912             }
913
914             (ForAll(a_clause), ForAll(b_clause)) => {
915                 let clause = relation.relate(a_clause, b_clause)?;
916                 Ok(ForAll(clause))
917             }
918
919             _ => Err(TypeError::Mismatch),
920         }
921     }
922 }
923
924 impl<'tcx> Relate<'tcx> for traits::Clauses<'tcx> {
925     fn relate<'a, 'gcx, R>(
926         relation: &mut R,
927         a: &traits::Clauses<'tcx>,
928         b: &traits::Clauses<'tcx>
929     ) -> RelateResult<'tcx, traits::Clauses<'tcx>>
930         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
931     {
932         if a.len() != b.len() {
933             return Err(TypeError::Mismatch);
934         }
935
936         let tcx = relation.tcx();
937         let clauses = a.iter().zip(b.iter()).map(|(a, b)| relation.relate(a, b));
938         Ok(tcx.mk_clauses(clauses)?)
939     }
940 }
941
942 impl<'tcx> Relate<'tcx> for traits::ProgramClause<'tcx> {
943     fn relate<'a, 'gcx, R>(
944         relation: &mut R,
945         a: &traits::ProgramClause<'tcx>,
946         b: &traits::ProgramClause<'tcx>
947     ) -> RelateResult<'tcx, traits::ProgramClause<'tcx>>
948         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
949     {
950         Ok(traits::ProgramClause {
951             goal: relation.relate(&a.goal, &b.goal)?,
952             hypotheses: relation.relate(&a.hypotheses, &b.hypotheses)?,
953             category: traits::ProgramClauseCategory::Other,
954         })
955     }
956 }
957
958 impl<'tcx> Relate<'tcx> for traits::Environment<'tcx> {
959     fn relate<'a, 'gcx, R>(
960         relation: &mut R,
961         a: &traits::Environment<'tcx>,
962         b: &traits::Environment<'tcx>
963     ) -> RelateResult<'tcx, traits::Environment<'tcx>>
964         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
965     {
966         Ok(traits::Environment {
967             clauses: relation.relate(&a.clauses, &b.clauses)?,
968         })
969     }
970 }
971
972 impl<'tcx, G> Relate<'tcx> for traits::InEnvironment<'tcx, G>
973     where G: Relate<'tcx>
974 {
975     fn relate<'a, 'gcx, R>(
976         relation: &mut R,
977         a: &traits::InEnvironment<'tcx, G>,
978         b: &traits::InEnvironment<'tcx, G>
979     ) -> RelateResult<'tcx, traits::InEnvironment<'tcx, G>>
980         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'tcx, 'tcx: 'a
981     {
982         Ok(traits::InEnvironment {
983             environment: relation.relate(&a.environment, &b.environment)?,
984             goal: relation.relate(&a.goal, &b.goal)?,
985         })
986     }
987 }
988
989 ///////////////////////////////////////////////////////////////////////////
990 // Error handling
991
992 pub fn expected_found<'a, 'gcx, 'tcx, R, T>(relation: &mut R,
993                                             a: &T,
994                                             b: &T)
995                                             -> ExpectedFound<T>
996     where R: TypeRelation<'a, 'gcx, 'tcx>, T: Clone, 'gcx: 'a+'tcx, 'tcx: 'a
997 {
998     expected_found_bool(relation.a_is_expected(), a, b)
999 }
1000
1001 pub fn expected_found_bool<T>(a_is_expected: bool,
1002                               a: &T,
1003                               b: &T)
1004                               -> ExpectedFound<T>
1005     where T: Clone
1006 {
1007     let a = a.clone();
1008     let b = b.clone();
1009     if a_is_expected {
1010         ExpectedFound {expected: a, found: b}
1011     } else {
1012         ExpectedFound {expected: b, found: a}
1013     }
1014 }