]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/relate.rs
Auto merge of #54720 - davidtwco:issue-51191, r=nikomatsakis
[rust.git] / src / librustc / ty / relate.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Generalized type relating mechanism. A type relation R relates a
12 //! pair of values (A, B). A and B are usually types or regions but
13 //! can be other things. Examples of type relations are subtyping,
14 //! type equality, etc.
15
16 use hir::def_id::DefId;
17 use mir::interpret::ConstValue;
18 use ty::subst::{Kind, UnpackedKind, Substs};
19 use ty::{self, Ty, TyCtxt, TypeFoldable};
20 use ty::error::{ExpectedFound, TypeError};
21 use mir::interpret::GlobalId;
22 use util::common::ErrorReported;
23 use syntax_pos::DUMMY_SP;
24 use std::rc::Rc;
25 use std::iter;
26 use rustc_target::spec::abi;
27 use hir as ast;
28
29 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
30
31 #[derive(Clone, Debug)]
32 pub enum Cause {
33     ExistentialRegionBound, // relating an existential region bound
34 }
35
36 pub trait TypeRelation<'a, 'gcx: 'a+'tcx, 'tcx: 'a> : Sized {
37     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx>;
38
39     /// Returns a static string we can use for printouts.
40     fn tag(&self) -> &'static str;
41
42     /// Returns true if the value `a` is the "expected" type in the
43     /// relation. Just affects error messages.
44     fn a_is_expected(&self) -> bool;
45
46     fn with_cause<F,R>(&mut self, _cause: Cause, f: F) -> R
47         where F: FnOnce(&mut Self) -> R
48     {
49         f(self)
50     }
51
52     /// Generic relation routine suitable for most anything.
53     fn relate<T: Relate<'tcx>>(&mut self, a: &T, b: &T) -> RelateResult<'tcx, T> {
54         Relate::relate(self, a, b)
55     }
56
57     /// Relate the two substitutions for the given item. The default
58     /// is to look up the variance for the item and proceed
59     /// accordingly.
60     fn relate_item_substs(&mut self,
61                           item_def_id: DefId,
62                           a_subst: &'tcx Substs<'tcx>,
63                           b_subst: &'tcx Substs<'tcx>)
64                           -> RelateResult<'tcx, &'tcx Substs<'tcx>>
65     {
66         debug!("relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
67                item_def_id,
68                a_subst,
69                b_subst);
70
71         let opt_variances = self.tcx().variances_of(item_def_id);
72         relate_substs(self, Some(&opt_variances), a_subst, b_subst)
73     }
74
75     /// Switch variance for the purpose of relating `a` and `b`.
76     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
77                                              variance: ty::Variance,
78                                              a: &T,
79                                              b: &T)
80                                              -> RelateResult<'tcx, T>;
81
82     // Overrideable relations. You shouldn't typically call these
83     // directly, instead call `relate()`, which in turn calls
84     // these. This is both more uniform but also allows us to add
85     // additional hooks for other types in the future if needed
86     // without making older code, which called `relate`, obsolete.
87
88     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>)
89            -> RelateResult<'tcx, Ty<'tcx>>;
90
91     fn regions(&mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>)
92                -> RelateResult<'tcx, ty::Region<'tcx>>;
93
94     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
95                   -> RelateResult<'tcx, ty::Binder<T>>
96         where T: Relate<'tcx>;
97 }
98
99 pub trait Relate<'tcx>: TypeFoldable<'tcx> {
100     fn relate<'a, 'gcx, R>(relation: &mut R, a: &Self, b: &Self)
101                            -> RelateResult<'tcx, Self>
102         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a;
103 }
104
105 ///////////////////////////////////////////////////////////////////////////
106 // Relate impls
107
108 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
109     fn relate<'a, 'gcx, R>(relation: &mut R,
110                            a: &ty::TypeAndMut<'tcx>,
111                            b: &ty::TypeAndMut<'tcx>)
112                            -> RelateResult<'tcx, ty::TypeAndMut<'tcx>>
113         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
114     {
115         debug!("{}.mts({:?}, {:?})",
116                relation.tag(),
117                a,
118                b);
119         if a.mutbl != b.mutbl {
120             Err(TypeError::Mutability)
121         } else {
122             let mutbl = a.mutbl;
123             let variance = match mutbl {
124                 ast::Mutability::MutImmutable => ty::Covariant,
125                 ast::Mutability::MutMutable => ty::Invariant,
126             };
127             let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
128             Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
129         }
130     }
131 }
132
133 pub fn relate_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
134                                         variances: Option<&Vec<ty::Variance>>,
135                                         a_subst: &'tcx Substs<'tcx>,
136                                         b_subst: &'tcx Substs<'tcx>)
137                                         -> RelateResult<'tcx, &'tcx Substs<'tcx>>
138     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
139 {
140     let tcx = relation.tcx();
141
142     let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
143         let variance = variances.map_or(ty::Invariant, |v| v[i]);
144         relation.relate_with_variance(variance, a, b)
145     });
146
147     Ok(tcx.mk_substs(params)?)
148 }
149
150 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
151     fn relate<'a, 'gcx, R>(relation: &mut R,
152                            a: &ty::FnSig<'tcx>,
153                            b: &ty::FnSig<'tcx>)
154                            -> RelateResult<'tcx, ty::FnSig<'tcx>>
155         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
156     {
157         let tcx = relation.tcx();
158
159         if a.variadic != b.variadic {
160             return Err(TypeError::VariadicMismatch(
161                 expected_found(relation, &a.variadic, &b.variadic)));
162         }
163         let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
164         let abi = relation.relate(&a.abi, &b.abi)?;
165
166         if a.inputs().len() != b.inputs().len() {
167             return Err(TypeError::ArgCount);
168         }
169
170         let inputs_and_output = a.inputs().iter().cloned()
171             .zip(b.inputs().iter().cloned())
172             .map(|x| (x, false))
173             .chain(iter::once(((a.output(), b.output()), true)))
174             .map(|((a, b), is_output)| {
175                 if is_output {
176                     relation.relate(&a, &b)
177                 } else {
178                     relation.relate_with_variance(ty::Contravariant, &a, &b)
179                 }
180             });
181         Ok(ty::FnSig {
182             inputs_and_output: tcx.mk_type_list(inputs_and_output)?,
183             variadic: a.variadic,
184             unsafety,
185             abi,
186         })
187     }
188 }
189
190 impl<'tcx> Relate<'tcx> for ast::Unsafety {
191     fn relate<'a, 'gcx, R>(relation: &mut R,
192                            a: &ast::Unsafety,
193                            b: &ast::Unsafety)
194                            -> RelateResult<'tcx, ast::Unsafety>
195         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
196     {
197         if a != b {
198             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
199         } else {
200             Ok(*a)
201         }
202     }
203 }
204
205 impl<'tcx> Relate<'tcx> for abi::Abi {
206     fn relate<'a, 'gcx, R>(relation: &mut R,
207                            a: &abi::Abi,
208                            b: &abi::Abi)
209                            -> RelateResult<'tcx, abi::Abi>
210         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
211     {
212         if a == b {
213             Ok(*a)
214         } else {
215             Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
216         }
217     }
218 }
219
220 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
221     fn relate<'a, 'gcx, R>(relation: &mut R,
222                            a: &ty::ProjectionTy<'tcx>,
223                            b: &ty::ProjectionTy<'tcx>)
224                            -> RelateResult<'tcx, ty::ProjectionTy<'tcx>>
225         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
226     {
227         if a.item_def_id != b.item_def_id {
228             Err(TypeError::ProjectionMismatched(
229                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
230         } else {
231             let substs = relation.relate(&a.substs, &b.substs)?;
232             Ok(ty::ProjectionTy {
233                 item_def_id: a.item_def_id,
234                 substs: &substs,
235             })
236         }
237     }
238 }
239
240 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
241     fn relate<'a, 'gcx, R>(relation: &mut R,
242                            a: &ty::ExistentialProjection<'tcx>,
243                            b: &ty::ExistentialProjection<'tcx>)
244                            -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>>
245         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
246     {
247         if a.item_def_id != b.item_def_id {
248             Err(TypeError::ProjectionMismatched(
249                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
250         } else {
251             let ty = relation.relate(&a.ty, &b.ty)?;
252             let substs = relation.relate(&a.substs, &b.substs)?;
253             Ok(ty::ExistentialProjection {
254                 item_def_id: a.item_def_id,
255                 substs,
256                 ty,
257             })
258         }
259     }
260 }
261
262 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
263     fn relate<'a, 'gcx, R>(relation: &mut R,
264                            a: &Vec<ty::PolyExistentialProjection<'tcx>>,
265                            b: &Vec<ty::PolyExistentialProjection<'tcx>>)
266                            -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>>
267         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
268     {
269         // To be compatible, `a` and `b` must be for precisely the
270         // same set of traits and item names. We always require that
271         // projection bounds lists are sorted by trait-def-id and item-name,
272         // so we can just iterate through the lists pairwise, so long as they are the
273         // same length.
274         if a.len() != b.len() {
275             Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
276         } else {
277             a.iter().zip(b)
278                 .map(|(a, b)| relation.relate(a, b))
279                 .collect()
280         }
281     }
282 }
283
284 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
285     fn relate<'a, 'gcx, R>(relation: &mut R,
286                            a: &ty::TraitRef<'tcx>,
287                            b: &ty::TraitRef<'tcx>)
288                            -> RelateResult<'tcx, ty::TraitRef<'tcx>>
289         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
290     {
291         // Different traits cannot be related
292         if a.def_id != b.def_id {
293             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
294         } else {
295             let substs = relate_substs(relation, None, a.substs, b.substs)?;
296             Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
297         }
298     }
299 }
300
301 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
302     fn relate<'a, 'gcx, R>(relation: &mut R,
303                            a: &ty::ExistentialTraitRef<'tcx>,
304                            b: &ty::ExistentialTraitRef<'tcx>)
305                            -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>>
306         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
307     {
308         // Different traits cannot be related
309         if a.def_id != b.def_id {
310             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
311         } else {
312             let substs = relate_substs(relation, None, a.substs, b.substs)?;
313             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
314         }
315     }
316 }
317
318 #[derive(Debug, Clone)]
319 struct GeneratorWitness<'tcx>(&'tcx ty::List<Ty<'tcx>>);
320
321 TupleStructTypeFoldableImpl! {
322     impl<'tcx> TypeFoldable<'tcx> for GeneratorWitness<'tcx> {
323         a
324     }
325 }
326
327 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
328     fn relate<'a, 'gcx, R>(relation: &mut R,
329                            a: &GeneratorWitness<'tcx>,
330                            b: &GeneratorWitness<'tcx>)
331                            -> RelateResult<'tcx, GeneratorWitness<'tcx>>
332         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
333     {
334         assert!(a.0.len() == b.0.len());
335         let tcx = relation.tcx();
336         let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
337         Ok(GeneratorWitness(types))
338     }
339 }
340
341 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
342     fn relate<'a, 'gcx, R>(relation: &mut R,
343                            a: &Ty<'tcx>,
344                            b: &Ty<'tcx>)
345                            -> RelateResult<'tcx, Ty<'tcx>>
346         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
347     {
348         relation.tys(a, b)
349     }
350 }
351
352 /// The main "type relation" routine. Note that this does not handle
353 /// inference artifacts, so you should filter those out before calling
354 /// it.
355 pub fn super_relate_tys<'a, 'gcx, 'tcx, R>(relation: &mut R,
356                                            a: Ty<'tcx>,
357                                            b: Ty<'tcx>)
358                                            -> RelateResult<'tcx, Ty<'tcx>>
359     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
360 {
361     let tcx = relation.tcx();
362     let a_sty = &a.sty;
363     let b_sty = &b.sty;
364     debug!("super_relate_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
365     match (a_sty, b_sty) {
366         (&ty::Infer(_), _) |
367         (_, &ty::Infer(_)) =>
368         {
369             // The caller should handle these cases!
370             bug!("var types encountered in super_relate_tys")
371         }
372
373         (&ty::Error, _) | (_, &ty::Error) =>
374         {
375             Ok(tcx.types.err)
376         }
377
378         (&ty::Never, _) |
379         (&ty::Char, _) |
380         (&ty::Bool, _) |
381         (&ty::Int(_), _) |
382         (&ty::Uint(_), _) |
383         (&ty::Float(_), _) |
384         (&ty::Str, _)
385             if a == b =>
386         {
387             Ok(a)
388         }
389
390         (&ty::Param(ref a_p), &ty::Param(ref b_p))
391             if a_p.idx == b_p.idx =>
392         {
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             assert_eq!(sz_a.ty, tcx.types.usize);
472             assert_eq!(sz_b.ty, tcx.types.usize);
473             let to_u64 = |x: &'tcx ty::Const<'tcx>| -> Result<u64, ErrorReported> {
474                 if let Some(s) = x.assert_usize(tcx) {
475                     return Ok(s);
476                 }
477                 match x.val {
478                     ConstValue::Unevaluated(def_id, substs) => {
479                         // FIXME(eddyb) get the right param_env.
480                         let param_env = ty::ParamEnv::empty();
481                         match tcx.lift_to_global(&substs) {
482                             Some(substs) => {
483                                 let instance = ty::Instance::resolve(
484                                     tcx.global_tcx(),
485                                     param_env,
486                                     def_id,
487                                     substs,
488                                 );
489                                 if let Some(instance) = instance {
490                                     let cid = GlobalId {
491                                         instance,
492                                         promoted: None
493                                     };
494                                     if let Some(s) = tcx.const_eval(param_env.and(cid))
495                                                         .ok()
496                                                         .map(|c| c.unwrap_usize(tcx)) {
497                                         return Ok(s)
498                                     }
499                                 }
500                             },
501                             None => {}
502                         }
503                         tcx.sess.delay_span_bug(tcx.def_span(def_id),
504                             "array length could not be evaluated");
505                         Err(ErrorReported)
506                     }
507                     _ => {
508                         tcx.sess.delay_span_bug(DUMMY_SP,
509                             &format!("arrays should not have {:?} as length", x));
510                         Err(ErrorReported)
511                     }
512                 }
513             };
514             match (to_u64(sz_a), to_u64(sz_b)) {
515                 (Ok(sz_a_u64), Ok(sz_b_u64)) => {
516                     if sz_a_u64 == sz_b_u64 {
517                         Ok(tcx.mk_ty(ty::Array(t, sz_a)))
518                     } else {
519                         Err(TypeError::FixedArraySize(
520                             expected_found(relation, &sz_a_u64, &sz_b_u64)))
521                     }
522                 }
523                 // We reported an error or will ICE, so we can return Error.
524                 (Err(ErrorReported), _) | (_, Err(ErrorReported)) => {
525                     Ok(tcx.types.err)
526                 }
527             }
528         }
529
530         (&ty::Slice(a_t), &ty::Slice(b_t)) =>
531         {
532             let t = relation.relate(&a_t, &b_t)?;
533             Ok(tcx.mk_slice(t))
534         }
535
536         (&ty::Tuple(as_), &ty::Tuple(bs)) =>
537         {
538             if as_.len() == bs.len() {
539                 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| relation.relate(a, b)))?)
540             } else if !(as_.is_empty() || bs.is_empty()) {
541                 Err(TypeError::TupleSize(
542                     expected_found(relation, &as_.len(), &bs.len())))
543             } else {
544                 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
545             }
546         }
547
548         (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs))
549             if a_def_id == b_def_id =>
550         {
551             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
552             Ok(tcx.mk_fn_def(a_def_id, substs))
553         }
554
555         (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) =>
556         {
557             let fty = relation.relate(&a_fty, &b_fty)?;
558             Ok(tcx.mk_fn_ptr(fty))
559         }
560
561         (&ty::Projection(ref a_data), &ty::Projection(ref b_data)) =>
562         {
563             let projection_ty = relation.relate(a_data, b_data)?;
564             Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
565         }
566
567         (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs))
568             if a_def_id == b_def_id =>
569         {
570             let substs = relate_substs(relation, None, a_substs, b_substs)?;
571             Ok(tcx.mk_opaque(a_def_id, substs))
572         }
573
574         _ =>
575         {
576             Err(TypeError::Sorts(expected_found(relation, &a, &b)))
577         }
578     }
579 }
580
581 impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::ExistentialPredicate<'tcx>> {
582     fn relate<'a, 'gcx, R>(relation: &mut R,
583                            a: &Self,
584                            b: &Self)
585         -> RelateResult<'tcx, Self>
586             where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a {
587
588         if a.len() != b.len() {
589             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
590         }
591
592         let tcx = relation.tcx();
593         let v = a.iter().zip(b.iter()).map(|(ep_a, ep_b)| {
594             use ty::ExistentialPredicate::*;
595             match (*ep_a, *ep_b) {
596                 (Trait(ref a), Trait(ref b)) => Ok(Trait(relation.relate(a, b)?)),
597                 (Projection(ref a), Projection(ref b)) => Ok(Projection(relation.relate(a, b)?)),
598                 (AutoTrait(ref a), AutoTrait(ref b)) if a == b => Ok(AutoTrait(*a)),
599                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)))
600             }
601         });
602         Ok(tcx.mk_existential_predicates(v)?)
603     }
604 }
605
606 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
607     fn relate<'a, 'gcx, R>(relation: &mut R,
608                            a: &ty::ClosureSubsts<'tcx>,
609                            b: &ty::ClosureSubsts<'tcx>)
610                            -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
611         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
612     {
613         let substs = relate_substs(relation, None, a.substs, b.substs)?;
614         Ok(ty::ClosureSubsts { substs })
615     }
616 }
617
618 impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> {
619     fn relate<'a, 'gcx, R>(relation: &mut R,
620                            a: &ty::GeneratorSubsts<'tcx>,
621                            b: &ty::GeneratorSubsts<'tcx>)
622                            -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>>
623         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
624     {
625         let substs = relate_substs(relation, None, a.substs, b.substs)?;
626         Ok(ty::GeneratorSubsts { substs })
627     }
628 }
629
630 impl<'tcx> Relate<'tcx> for &'tcx Substs<'tcx> {
631     fn relate<'a, 'gcx, R>(relation: &mut R,
632                            a: &&'tcx Substs<'tcx>,
633                            b: &&'tcx Substs<'tcx>)
634                            -> RelateResult<'tcx, &'tcx Substs<'tcx>>
635         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
636     {
637         relate_substs(relation, None, a, b)
638     }
639 }
640
641 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
642     fn relate<'a, 'gcx, R>(relation: &mut R,
643                            a: &ty::Region<'tcx>,
644                            b: &ty::Region<'tcx>)
645                            -> RelateResult<'tcx, ty::Region<'tcx>>
646         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
647     {
648         relation.regions(*a, *b)
649     }
650 }
651
652 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
653     fn relate<'a, 'gcx, R>(relation: &mut R,
654                            a: &ty::Binder<T>,
655                            b: &ty::Binder<T>)
656                            -> RelateResult<'tcx, ty::Binder<T>>
657         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
658     {
659         relation.binders(a, b)
660     }
661 }
662
663 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
664     fn relate<'a, 'gcx, R>(relation: &mut R,
665                            a: &Rc<T>,
666                            b: &Rc<T>)
667                            -> RelateResult<'tcx, Rc<T>>
668         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
669     {
670         let a: &T = a;
671         let b: &T = b;
672         Ok(Rc::new(relation.relate(a, b)?))
673     }
674 }
675
676 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
677     fn relate<'a, 'gcx, R>(relation: &mut R,
678                            a: &Box<T>,
679                            b: &Box<T>)
680                            -> RelateResult<'tcx, Box<T>>
681         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
682     {
683         let a: &T = a;
684         let b: &T = b;
685         Ok(Box::new(relation.relate(a, b)?))
686     }
687 }
688
689 impl<'tcx> Relate<'tcx> for Kind<'tcx> {
690     fn relate<'a, 'gcx, R>(
691         relation: &mut R,
692         a: &Kind<'tcx>,
693         b: &Kind<'tcx>
694     ) -> RelateResult<'tcx, Kind<'tcx>>
695     where
696         R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a,
697     {
698         match (a.unpack(), b.unpack()) {
699             (UnpackedKind::Lifetime(a_lt), UnpackedKind::Lifetime(b_lt)) => {
700                 Ok(relation.relate(&a_lt, &b_lt)?.into())
701             }
702             (UnpackedKind::Type(a_ty), UnpackedKind::Type(b_ty)) => {
703                 Ok(relation.relate(&a_ty, &b_ty)?.into())
704             }
705             (UnpackedKind::Lifetime(unpacked), x) => {
706                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
707             }
708             (UnpackedKind::Type(unpacked), x) => {
709                 bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
710             }
711         }
712     }
713 }
714
715 ///////////////////////////////////////////////////////////////////////////
716 // Error handling
717
718 pub fn expected_found<'a, 'gcx, 'tcx, R, T>(relation: &mut R,
719                                             a: &T,
720                                             b: &T)
721                                             -> ExpectedFound<T>
722     where R: TypeRelation<'a, 'gcx, 'tcx>, T: Clone, 'gcx: 'a+'tcx, 'tcx: 'a
723 {
724     expected_found_bool(relation.a_is_expected(), a, b)
725 }
726
727 pub fn expected_found_bool<T>(a_is_expected: bool,
728                               a: &T,
729                               b: &T)
730                               -> ExpectedFound<T>
731     where T: Clone
732 {
733     let a = a.clone();
734     let b = b.clone();
735     if a_is_expected {
736         ExpectedFound {expected: a, found: b}
737     } else {
738         ExpectedFound {expected: b, found: a}
739     }
740 }