]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/relate.rs
refactor `ParamEnv::empty(Reveal)` into two distinct methods
[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 middle::const_val::ConstVal;
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, Value, PrimVal};
22 use util::common::ErrorReported;
23 use std::rc::Rc;
24 use std::iter;
25 use syntax::abi;
26 use hir as ast;
27 use rustc_data_structures::accumulate_vec::AccumulateVec;
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         if a.variadic != b.variadic {
158             return Err(TypeError::VariadicMismatch(
159                 expected_found(relation, &a.variadic, &b.variadic)));
160         }
161         let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
162         let abi = relation.relate(&a.abi, &b.abi)?;
163
164         if a.inputs().len() != b.inputs().len() {
165             return Err(TypeError::ArgCount);
166         }
167
168         let inputs_and_output = a.inputs().iter().cloned()
169             .zip(b.inputs().iter().cloned())
170             .map(|x| (x, false))
171             .chain(iter::once(((a.output(), b.output()), true)))
172             .map(|((a, b), is_output)| {
173                 if is_output {
174                     relation.relate(&a, &b)
175                 } else {
176                     relation.relate_with_variance(ty::Contravariant, &a, &b)
177                 }
178             }).collect::<Result<AccumulateVec<[_; 8]>, _>>()?;
179         Ok(ty::FnSig {
180             inputs_and_output: relation.tcx().intern_type_list(&inputs_and_output),
181             variadic: a.variadic,
182             unsafety,
183             abi,
184         })
185     }
186 }
187
188 impl<'tcx> Relate<'tcx> for ast::Unsafety {
189     fn relate<'a, 'gcx, R>(relation: &mut R,
190                            a: &ast::Unsafety,
191                            b: &ast::Unsafety)
192                            -> RelateResult<'tcx, ast::Unsafety>
193         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
194     {
195         if a != b {
196             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
197         } else {
198             Ok(*a)
199         }
200     }
201 }
202
203 impl<'tcx> Relate<'tcx> for abi::Abi {
204     fn relate<'a, 'gcx, R>(relation: &mut R,
205                            a: &abi::Abi,
206                            b: &abi::Abi)
207                            -> RelateResult<'tcx, abi::Abi>
208         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
209     {
210         if a == b {
211             Ok(*a)
212         } else {
213             Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
214         }
215     }
216 }
217
218 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
219     fn relate<'a, 'gcx, R>(relation: &mut R,
220                            a: &ty::ProjectionTy<'tcx>,
221                            b: &ty::ProjectionTy<'tcx>)
222                            -> RelateResult<'tcx, ty::ProjectionTy<'tcx>>
223         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
224     {
225         if a.item_def_id != b.item_def_id {
226             Err(TypeError::ProjectionMismatched(
227                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
228         } else {
229             let substs = relation.relate(&a.substs, &b.substs)?;
230             Ok(ty::ProjectionTy {
231                 item_def_id: a.item_def_id,
232                 substs: &substs,
233             })
234         }
235     }
236 }
237
238 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
239     fn relate<'a, 'gcx, R>(relation: &mut R,
240                            a: &ty::ExistentialProjection<'tcx>,
241                            b: &ty::ExistentialProjection<'tcx>)
242                            -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>>
243         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
244     {
245         if a.item_def_id != b.item_def_id {
246             Err(TypeError::ProjectionMismatched(
247                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
248         } else {
249             let ty = relation.relate(&a.ty, &b.ty)?;
250             let substs = relation.relate(&a.substs, &b.substs)?;
251             Ok(ty::ExistentialProjection {
252                 item_def_id: a.item_def_id,
253                 substs,
254                 ty,
255             })
256         }
257     }
258 }
259
260 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
261     fn relate<'a, 'gcx, R>(relation: &mut R,
262                            a: &Vec<ty::PolyExistentialProjection<'tcx>>,
263                            b: &Vec<ty::PolyExistentialProjection<'tcx>>)
264                            -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>>
265         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
266     {
267         // To be compatible, `a` and `b` must be for precisely the
268         // same set of traits and item names. We always require that
269         // projection bounds lists are sorted by trait-def-id and item-name,
270         // so we can just iterate through the lists pairwise, so long as they are the
271         // same length.
272         if a.len() != b.len() {
273             Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
274         } else {
275             a.iter().zip(b)
276                 .map(|(a, b)| relation.relate(a, b))
277                 .collect()
278         }
279     }
280 }
281
282 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
283     fn relate<'a, 'gcx, R>(relation: &mut R,
284                            a: &ty::TraitRef<'tcx>,
285                            b: &ty::TraitRef<'tcx>)
286                            -> RelateResult<'tcx, ty::TraitRef<'tcx>>
287         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
288     {
289         // Different traits cannot be related
290         if a.def_id != b.def_id {
291             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
292         } else {
293             let substs = relate_substs(relation, None, a.substs, b.substs)?;
294             Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
295         }
296     }
297 }
298
299 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
300     fn relate<'a, 'gcx, R>(relation: &mut R,
301                            a: &ty::ExistentialTraitRef<'tcx>,
302                            b: &ty::ExistentialTraitRef<'tcx>)
303                            -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>>
304         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
305     {
306         // Different traits cannot be related
307         if a.def_id != b.def_id {
308             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
309         } else {
310             let substs = relate_substs(relation, None, a.substs, b.substs)?;
311             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
312         }
313     }
314 }
315
316 #[derive(Debug, Clone)]
317 struct GeneratorWitness<'tcx>(&'tcx ty::Slice<Ty<'tcx>>);
318
319 TupleStructTypeFoldableImpl! {
320     impl<'tcx> TypeFoldable<'tcx> for GeneratorWitness<'tcx> {
321         a
322     }
323 }
324
325 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
326     fn relate<'a, 'gcx, R>(relation: &mut R,
327                            a: &GeneratorWitness<'tcx>,
328                            b: &GeneratorWitness<'tcx>)
329                            -> RelateResult<'tcx, GeneratorWitness<'tcx>>
330         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
331     {
332         assert!(a.0.len() == b.0.len());
333         let tcx = relation.tcx();
334         let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
335         Ok(GeneratorWitness(types))
336     }
337 }
338
339 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
340     fn relate<'a, 'gcx, R>(relation: &mut R,
341                            a: &Ty<'tcx>,
342                            b: &Ty<'tcx>)
343                            -> RelateResult<'tcx, Ty<'tcx>>
344         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
345     {
346         relation.tys(a, b)
347     }
348 }
349
350 /// The main "type relation" routine. Note that this does not handle
351 /// inference artifacts, so you should filter those out before calling
352 /// it.
353 pub fn super_relate_tys<'a, 'gcx, 'tcx, R>(relation: &mut R,
354                                            a: Ty<'tcx>,
355                                            b: Ty<'tcx>)
356                                            -> RelateResult<'tcx, Ty<'tcx>>
357     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
358 {
359     let tcx = relation.tcx();
360     let a_sty = &a.sty;
361     let b_sty = &b.sty;
362     debug!("super_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
363     match (a_sty, b_sty) {
364         (&ty::TyInfer(_), _) |
365         (_, &ty::TyInfer(_)) =>
366         {
367             // The caller should handle these cases!
368             bug!("var types encountered in super_relate_tys")
369         }
370
371         (&ty::TyError, _) | (_, &ty::TyError) =>
372         {
373             Ok(tcx.types.err)
374         }
375
376         (&ty::TyNever, _) |
377         (&ty::TyChar, _) |
378         (&ty::TyBool, _) |
379         (&ty::TyInt(_), _) |
380         (&ty::TyUint(_), _) |
381         (&ty::TyFloat(_), _) |
382         (&ty::TyStr, _)
383             if a == b =>
384         {
385             Ok(a)
386         }
387
388         (&ty::TyParam(ref a_p), &ty::TyParam(ref b_p))
389             if a_p.idx == b_p.idx =>
390         {
391             Ok(a)
392         }
393
394         (&ty::TyAdt(a_def, a_substs), &ty::TyAdt(b_def, b_substs))
395             if a_def == b_def =>
396         {
397             let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
398             Ok(tcx.mk_adt(a_def, substs))
399         }
400
401         (&ty::TyForeign(a_id), &ty::TyForeign(b_id))
402             if a_id == b_id =>
403         {
404             Ok(tcx.mk_foreign(a_id))
405         }
406
407         (&ty::TyDynamic(ref a_obj, ref a_region), &ty::TyDynamic(ref b_obj, ref b_region)) => {
408             let region_bound = relation.with_cause(Cause::ExistentialRegionBound,
409                                                        |relation| {
410                                                            relation.relate_with_variance(
411                                                                ty::Contravariant,
412                                                                a_region,
413                                                                b_region)
414                                                        })?;
415             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
416         }
417
418         (&ty::TyGenerator(a_id, a_substs, a_interior),
419          &ty::TyGenerator(b_id, b_substs, b_interior))
420             if a_id == b_id =>
421         {
422             // All TyGenerator types with the same id represent
423             // the (anonymous) type of the same generator expression. So
424             // all of their regions should be equated.
425             let substs = relation.relate(&a_substs, &b_substs)?;
426             let interior = relation.relate(&a_interior, &b_interior)?;
427             Ok(tcx.mk_generator(a_id, substs, interior))
428         }
429
430         (&ty::TyGeneratorWitness(a_types), &ty::TyGeneratorWitness(b_types)) =>
431         {
432             // Wrap our types with a temporary GeneratorWitness struct
433             // inside the binder so we can related them
434             let a_types = ty::Binder(GeneratorWitness(*a_types.skip_binder()));
435             let b_types = ty::Binder(GeneratorWitness(*b_types.skip_binder()));
436             // Then remove the GeneratorWitness for the result
437             let types = ty::Binder(relation.relate(&a_types, &b_types)?.skip_binder().0);
438             Ok(tcx.mk_generator_witness(types))
439         }
440
441         (&ty::TyClosure(a_id, a_substs),
442          &ty::TyClosure(b_id, b_substs))
443             if a_id == b_id =>
444         {
445             // All TyClosure types with the same id represent
446             // the (anonymous) type of the same closure expression. So
447             // all of their regions should be equated.
448             let substs = relation.relate(&a_substs, &b_substs)?;
449             Ok(tcx.mk_closure_from_closure_substs(a_id, substs))
450         }
451
452         (&ty::TyRawPtr(ref a_mt), &ty::TyRawPtr(ref b_mt)) =>
453         {
454             let mt = relation.relate(a_mt, b_mt)?;
455             Ok(tcx.mk_ptr(mt))
456         }
457
458         (&ty::TyRef(a_r, ref a_mt), &ty::TyRef(b_r, ref b_mt)) =>
459         {
460             let r = relation.relate_with_variance(ty::Contravariant, &a_r, &b_r)?;
461             let mt = relation.relate(a_mt, b_mt)?;
462             Ok(tcx.mk_ref(r, mt))
463         }
464
465         (&ty::TyArray(a_t, sz_a), &ty::TyArray(b_t, sz_b)) =>
466         {
467             let t = relation.relate(&a_t, &b_t)?;
468             assert_eq!(sz_a.ty, tcx.types.usize);
469             assert_eq!(sz_b.ty, tcx.types.usize);
470             let to_u64 = |x: &'tcx ty::Const<'tcx>| -> Result<u64, ErrorReported> {
471                 match x.val {
472                     ConstVal::Value(Value::ByVal(prim)) => Ok(prim.to_u64().unwrap()),
473                     ConstVal::Unevaluated(def_id, substs) => {
474                         // FIXME(eddyb) get the right param_env.
475                         let param_env = ty::ParamEnv::empty();
476                         match tcx.lift_to_global(&substs) {
477                             Some(substs) => {
478                                 let instance = ty::Instance::resolve(
479                                     tcx.global_tcx(),
480                                     param_env,
481                                     def_id,
482                                     substs,
483                                 );
484                                 if let Some(instance) = instance {
485                                     let cid = GlobalId {
486                                         instance,
487                                         promoted: None
488                                     };
489                                     match tcx.const_eval(param_env.and(cid)) {
490                                         Ok(&ty::Const {
491                                             val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))),
492                                             ..
493                                         }) => {
494                                             assert_eq!(b as u64 as u128, b);
495                                             return Ok(b as u64);
496                                         }
497                                         _ => {}
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                     _ => bug!("arrays should not have {:?} as length", x)
508                 }
509             };
510             match (to_u64(sz_a), to_u64(sz_b)) {
511                 (Ok(sz_a_u64), Ok(sz_b_u64)) => {
512                     if sz_a_u64 == sz_b_u64 {
513                         Ok(tcx.mk_ty(ty::TyArray(t, sz_a)))
514                     } else {
515                         Err(TypeError::FixedArraySize(
516                             expected_found(relation, &sz_a_u64, &sz_b_u64)))
517                     }
518                 }
519                 // We reported an error or will ICE, so we can return TyError.
520                 (Err(ErrorReported), _) | (_, Err(ErrorReported)) => {
521                     Ok(tcx.types.err)
522                 }
523             }
524         }
525
526         (&ty::TySlice(a_t), &ty::TySlice(b_t)) =>
527         {
528             let t = relation.relate(&a_t, &b_t)?;
529             Ok(tcx.mk_slice(t))
530         }
531
532         (&ty::TyTuple(as_, a_defaulted), &ty::TyTuple(bs, b_defaulted)) =>
533         {
534             if as_.len() == bs.len() {
535                 let defaulted = a_defaulted || b_defaulted;
536                 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| relation.relate(a, b)), defaulted)?)
537             } else if !(as_.is_empty() || bs.is_empty()) {
538                 Err(TypeError::TupleSize(
539                     expected_found(relation, &as_.len(), &bs.len())))
540             } else {
541                 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
542             }
543         }
544
545         (&ty::TyFnDef(a_def_id, a_substs), &ty::TyFnDef(b_def_id, b_substs))
546             if a_def_id == b_def_id =>
547         {
548             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
549             Ok(tcx.mk_fn_def(a_def_id, substs))
550         }
551
552         (&ty::TyFnPtr(a_fty), &ty::TyFnPtr(b_fty)) =>
553         {
554             let fty = relation.relate(&a_fty, &b_fty)?;
555             Ok(tcx.mk_fn_ptr(fty))
556         }
557
558         (&ty::TyProjection(ref a_data), &ty::TyProjection(ref b_data)) =>
559         {
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::TyAnon(a_def_id, a_substs), &ty::TyAnon(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_anon(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::Slice<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 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: substs })
612     }
613 }
614
615 impl<'tcx> Relate<'tcx> for ty::GeneratorInterior<'tcx> {
616     fn relate<'a, 'gcx, R>(relation: &mut R,
617                            a: &ty::GeneratorInterior<'tcx>,
618                            b: &ty::GeneratorInterior<'tcx>)
619                            -> RelateResult<'tcx, ty::GeneratorInterior<'tcx>>
620         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
621     {
622         assert_eq!(a.movable, b.movable);
623         let witness = relation.relate(&a.witness, &b.witness)?;
624         Ok(ty::GeneratorInterior { witness, movable: a.movable })
625     }
626 }
627
628 impl<'tcx> Relate<'tcx> for &'tcx Substs<'tcx> {
629     fn relate<'a, 'gcx, R>(relation: &mut R,
630                            a: &&'tcx Substs<'tcx>,
631                            b: &&'tcx Substs<'tcx>)
632                            -> RelateResult<'tcx, &'tcx Substs<'tcx>>
633         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
634     {
635         relate_substs(relation, None, a, b)
636     }
637 }
638
639 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
640     fn relate<'a, 'gcx, R>(relation: &mut R,
641                            a: &ty::Region<'tcx>,
642                            b: &ty::Region<'tcx>)
643                            -> RelateResult<'tcx, ty::Region<'tcx>>
644         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
645     {
646         relation.regions(*a, *b)
647     }
648 }
649
650 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
651     fn relate<'a, 'gcx, R>(relation: &mut R,
652                            a: &ty::Binder<T>,
653                            b: &ty::Binder<T>)
654                            -> RelateResult<'tcx, ty::Binder<T>>
655         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
656     {
657         relation.binders(a, b)
658     }
659 }
660
661 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
662     fn relate<'a, 'gcx, R>(relation: &mut R,
663                            a: &Rc<T>,
664                            b: &Rc<T>)
665                            -> RelateResult<'tcx, Rc<T>>
666         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
667     {
668         let a: &T = a;
669         let b: &T = b;
670         Ok(Rc::new(relation.relate(a, b)?))
671     }
672 }
673
674 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
675     fn relate<'a, 'gcx, R>(relation: &mut R,
676                            a: &Box<T>,
677                            b: &Box<T>)
678                            -> RelateResult<'tcx, Box<T>>
679         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
680     {
681         let a: &T = a;
682         let b: &T = b;
683         Ok(Box::new(relation.relate(a, b)?))
684     }
685 }
686
687 impl<'tcx> Relate<'tcx> for Kind<'tcx> {
688     fn relate<'a, 'gcx, R>(
689         relation: &mut R,
690         a: &Kind<'tcx>,
691         b: &Kind<'tcx>
692     ) -> RelateResult<'tcx, Kind<'tcx>>
693     where
694         R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a,
695     {
696         match (a.unpack(), b.unpack()) {
697             (UnpackedKind::Lifetime(a_lt), UnpackedKind::Lifetime(b_lt)) => {
698                 Ok(relation.relate(&a_lt, &b_lt)?.into())
699             }
700             (UnpackedKind::Type(a_ty), UnpackedKind::Type(b_ty)) => {
701                 Ok(relation.relate(&a_ty, &b_ty)?.into())
702             }
703             (UnpackedKind::Lifetime(_), _) | (UnpackedKind::Type(_), _) => bug!()
704         }
705     }
706 }
707
708 ///////////////////////////////////////////////////////////////////////////
709 // Error handling
710
711 pub fn expected_found<'a, 'gcx, 'tcx, R, T>(relation: &mut R,
712                                             a: &T,
713                                             b: &T)
714                                             -> ExpectedFound<T>
715     where R: TypeRelation<'a, 'gcx, 'tcx>, T: Clone, 'gcx: 'a+'tcx, 'tcx: 'a
716 {
717     expected_found_bool(relation.a_is_expected(), a, b)
718 }
719
720 pub fn expected_found_bool<T>(a_is_expected: bool,
721                               a: &T,
722                               b: &T)
723                               -> ExpectedFound<T>
724     where T: Clone
725 {
726     let a = a.clone();
727     let b = b.clone();
728     if a_is_expected {
729         ExpectedFound {expected: a, found: b}
730     } else {
731         ExpectedFound {expected: b, found: a}
732     }
733 }