]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/relate.rs
7f48f8c431fac08ae71befb3e8fef059945a825a
[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 traits::Reveal;
19 use ty::subst::{Kind, UnpackedKind, Substs};
20 use ty::{self, Ty, TyCtxt, TypeFoldable};
21 use ty::error::{ExpectedFound, TypeError};
22 use mir::interpret::{GlobalId, Value, PrimVal};
23 use util::common::ErrorReported;
24 use std::rc::Rc;
25 use std::iter;
26 use syntax::abi;
27 use hir as ast;
28 use rustc_data_structures::accumulate_vec::AccumulateVec;
29
30 pub type RelateResult<'tcx, T> = Result<T, TypeError<'tcx>>;
31
32 #[derive(Clone, Debug)]
33 pub enum Cause {
34     ExistentialRegionBound, // relating an existential region bound
35 }
36
37 pub trait TypeRelation<'a, 'gcx: 'a+'tcx, 'tcx: 'a> : Sized {
38     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx>;
39
40     /// Returns a static string we can use for printouts.
41     fn tag(&self) -> &'static str;
42
43     /// Returns true if the value `a` is the "expected" type in the
44     /// relation. Just affects error messages.
45     fn a_is_expected(&self) -> bool;
46
47     fn with_cause<F,R>(&mut self, _cause: Cause, f: F) -> R
48         where F: FnOnce(&mut Self) -> R
49     {
50         f(self)
51     }
52
53     /// Generic relation routine suitable for most anything.
54     fn relate<T: Relate<'tcx>>(&mut self, a: &T, b: &T) -> RelateResult<'tcx, T> {
55         Relate::relate(self, a, b)
56     }
57
58     /// Relate the two substitutions for the given item. The default
59     /// is to look up the variance for the item and proceed
60     /// accordingly.
61     fn relate_item_substs(&mut self,
62                           item_def_id: DefId,
63                           a_subst: &'tcx Substs<'tcx>,
64                           b_subst: &'tcx Substs<'tcx>)
65                           -> RelateResult<'tcx, &'tcx Substs<'tcx>>
66     {
67         debug!("relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})",
68                item_def_id,
69                a_subst,
70                b_subst);
71
72         let opt_variances = self.tcx().variances_of(item_def_id);
73         relate_substs(self, Some(&opt_variances), a_subst, b_subst)
74     }
75
76     /// Switch variance for the purpose of relating `a` and `b`.
77     fn relate_with_variance<T: Relate<'tcx>>(&mut self,
78                                              variance: ty::Variance,
79                                              a: &T,
80                                              b: &T)
81                                              -> RelateResult<'tcx, T>;
82
83     // Overrideable relations. You shouldn't typically call these
84     // directly, instead call `relate()`, which in turn calls
85     // these. This is both more uniform but also allows us to add
86     // additional hooks for other types in the future if needed
87     // without making older code, which called `relate`, obsolete.
88
89     fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>)
90            -> RelateResult<'tcx, Ty<'tcx>>;
91
92     fn regions(&mut self, a: ty::Region<'tcx>, b: ty::Region<'tcx>)
93                -> RelateResult<'tcx, ty::Region<'tcx>>;
94
95     fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
96                   -> RelateResult<'tcx, ty::Binder<T>>
97         where T: Relate<'tcx>;
98 }
99
100 pub trait Relate<'tcx>: TypeFoldable<'tcx> {
101     fn relate<'a, 'gcx, R>(relation: &mut R, a: &Self, b: &Self)
102                            -> RelateResult<'tcx, Self>
103         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a;
104 }
105
106 ///////////////////////////////////////////////////////////////////////////
107 // Relate impls
108
109 impl<'tcx> Relate<'tcx> for ty::TypeAndMut<'tcx> {
110     fn relate<'a, 'gcx, R>(relation: &mut R,
111                            a: &ty::TypeAndMut<'tcx>,
112                            b: &ty::TypeAndMut<'tcx>)
113                            -> RelateResult<'tcx, ty::TypeAndMut<'tcx>>
114         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
115     {
116         debug!("{}.mts({:?}, {:?})",
117                relation.tag(),
118                a,
119                b);
120         if a.mutbl != b.mutbl {
121             Err(TypeError::Mutability)
122         } else {
123             let mutbl = a.mutbl;
124             let variance = match mutbl {
125                 ast::Mutability::MutImmutable => ty::Covariant,
126                 ast::Mutability::MutMutable => ty::Invariant,
127             };
128             let ty = relation.relate_with_variance(variance, &a.ty, &b.ty)?;
129             Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
130         }
131     }
132 }
133
134 pub fn relate_substs<'a, 'gcx, 'tcx, R>(relation: &mut R,
135                                         variances: Option<&Vec<ty::Variance>>,
136                                         a_subst: &'tcx Substs<'tcx>,
137                                         b_subst: &'tcx Substs<'tcx>)
138                                         -> RelateResult<'tcx, &'tcx Substs<'tcx>>
139     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
140 {
141     let tcx = relation.tcx();
142
143     let params = a_subst.iter().zip(b_subst).enumerate().map(|(i, (a, b))| {
144         let variance = variances.map_or(ty::Invariant, |v| v[i]);
145         relation.relate_with_variance(variance, a, b)
146     });
147
148     Ok(tcx.mk_substs(params)?)
149 }
150
151 impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
152     fn relate<'a, 'gcx, R>(relation: &mut R,
153                            a: &ty::FnSig<'tcx>,
154                            b: &ty::FnSig<'tcx>)
155                            -> RelateResult<'tcx, ty::FnSig<'tcx>>
156         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
157     {
158         if a.variadic != b.variadic {
159             return Err(TypeError::VariadicMismatch(
160                 expected_found(relation, &a.variadic, &b.variadic)));
161         }
162         let unsafety = relation.relate(&a.unsafety, &b.unsafety)?;
163         let abi = relation.relate(&a.abi, &b.abi)?;
164
165         if a.inputs().len() != b.inputs().len() {
166             return Err(TypeError::ArgCount);
167         }
168
169         let inputs_and_output = a.inputs().iter().cloned()
170             .zip(b.inputs().iter().cloned())
171             .map(|x| (x, false))
172             .chain(iter::once(((a.output(), b.output()), true)))
173             .map(|((a, b), is_output)| {
174                 if is_output {
175                     relation.relate(&a, &b)
176                 } else {
177                     relation.relate_with_variance(ty::Contravariant, &a, &b)
178                 }
179             }).collect::<Result<AccumulateVec<[_; 8]>, _>>()?;
180         Ok(ty::FnSig {
181             inputs_and_output: relation.tcx().intern_type_list(&inputs_and_output),
182             variadic: a.variadic,
183             unsafety,
184             abi,
185         })
186     }
187 }
188
189 impl<'tcx> Relate<'tcx> for ast::Unsafety {
190     fn relate<'a, 'gcx, R>(relation: &mut R,
191                            a: &ast::Unsafety,
192                            b: &ast::Unsafety)
193                            -> RelateResult<'tcx, ast::Unsafety>
194         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
195     {
196         if a != b {
197             Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
198         } else {
199             Ok(*a)
200         }
201     }
202 }
203
204 impl<'tcx> Relate<'tcx> for abi::Abi {
205     fn relate<'a, 'gcx, R>(relation: &mut R,
206                            a: &abi::Abi,
207                            b: &abi::Abi)
208                            -> RelateResult<'tcx, abi::Abi>
209         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
210     {
211         if a == b {
212             Ok(*a)
213         } else {
214             Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
215         }
216     }
217 }
218
219 impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> {
220     fn relate<'a, 'gcx, R>(relation: &mut R,
221                            a: &ty::ProjectionTy<'tcx>,
222                            b: &ty::ProjectionTy<'tcx>)
223                            -> RelateResult<'tcx, ty::ProjectionTy<'tcx>>
224         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
225     {
226         if a.item_def_id != b.item_def_id {
227             Err(TypeError::ProjectionMismatched(
228                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
229         } else {
230             let substs = relation.relate(&a.substs, &b.substs)?;
231             Ok(ty::ProjectionTy {
232                 item_def_id: a.item_def_id,
233                 substs: &substs,
234             })
235         }
236     }
237 }
238
239 impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> {
240     fn relate<'a, 'gcx, R>(relation: &mut R,
241                            a: &ty::ExistentialProjection<'tcx>,
242                            b: &ty::ExistentialProjection<'tcx>)
243                            -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>>
244         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
245     {
246         if a.item_def_id != b.item_def_id {
247             Err(TypeError::ProjectionMismatched(
248                 expected_found(relation, &a.item_def_id, &b.item_def_id)))
249         } else {
250             let ty = relation.relate(&a.ty, &b.ty)?;
251             let substs = relation.relate(&a.substs, &b.substs)?;
252             Ok(ty::ExistentialProjection {
253                 item_def_id: a.item_def_id,
254                 substs,
255                 ty,
256             })
257         }
258     }
259 }
260
261 impl<'tcx> Relate<'tcx> for Vec<ty::PolyExistentialProjection<'tcx>> {
262     fn relate<'a, 'gcx, R>(relation: &mut R,
263                            a: &Vec<ty::PolyExistentialProjection<'tcx>>,
264                            b: &Vec<ty::PolyExistentialProjection<'tcx>>)
265                            -> RelateResult<'tcx, Vec<ty::PolyExistentialProjection<'tcx>>>
266         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
267     {
268         // To be compatible, `a` and `b` must be for precisely the
269         // same set of traits and item names. We always require that
270         // projection bounds lists are sorted by trait-def-id and item-name,
271         // so we can just iterate through the lists pairwise, so long as they are the
272         // same length.
273         if a.len() != b.len() {
274             Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
275         } else {
276             a.iter().zip(b)
277                 .map(|(a, b)| relation.relate(a, b))
278                 .collect()
279         }
280     }
281 }
282
283 impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> {
284     fn relate<'a, 'gcx, R>(relation: &mut R,
285                            a: &ty::TraitRef<'tcx>,
286                            b: &ty::TraitRef<'tcx>)
287                            -> RelateResult<'tcx, ty::TraitRef<'tcx>>
288         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
289     {
290         // Different traits cannot be related
291         if a.def_id != b.def_id {
292             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
293         } else {
294             let substs = relate_substs(relation, None, a.substs, b.substs)?;
295             Ok(ty::TraitRef { def_id: a.def_id, substs: substs })
296         }
297     }
298 }
299
300 impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> {
301     fn relate<'a, 'gcx, R>(relation: &mut R,
302                            a: &ty::ExistentialTraitRef<'tcx>,
303                            b: &ty::ExistentialTraitRef<'tcx>)
304                            -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>>
305         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
306     {
307         // Different traits cannot be related
308         if a.def_id != b.def_id {
309             Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
310         } else {
311             let substs = relate_substs(relation, None, a.substs, b.substs)?;
312             Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs: substs })
313         }
314     }
315 }
316
317 #[derive(Debug, Clone)]
318 struct GeneratorWitness<'tcx>(&'tcx ty::Slice<Ty<'tcx>>);
319
320 TupleStructTypeFoldableImpl! {
321     impl<'tcx> TypeFoldable<'tcx> for GeneratorWitness<'tcx> {
322         a
323     }
324 }
325
326 impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> {
327     fn relate<'a, 'gcx, R>(relation: &mut R,
328                            a: &GeneratorWitness<'tcx>,
329                            b: &GeneratorWitness<'tcx>)
330                            -> RelateResult<'tcx, GeneratorWitness<'tcx>>
331         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
332     {
333         assert!(a.0.len() == b.0.len());
334         let tcx = relation.tcx();
335         let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
336         Ok(GeneratorWitness(types))
337     }
338 }
339
340 impl<'tcx> Relate<'tcx> for Ty<'tcx> {
341     fn relate<'a, 'gcx, R>(relation: &mut R,
342                            a: &Ty<'tcx>,
343                            b: &Ty<'tcx>)
344                            -> RelateResult<'tcx, Ty<'tcx>>
345         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
346     {
347         relation.tys(a, b)
348     }
349 }
350
351 /// The main "type relation" routine. Note that this does not handle
352 /// inference artifacts, so you should filter those out before calling
353 /// it.
354 pub fn super_relate_tys<'a, 'gcx, 'tcx, R>(relation: &mut R,
355                                            a: Ty<'tcx>,
356                                            b: Ty<'tcx>)
357                                            -> RelateResult<'tcx, Ty<'tcx>>
358     where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
359 {
360     let tcx = relation.tcx();
361     let a_sty = &a.sty;
362     let b_sty = &b.sty;
363     debug!("super_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty);
364     match (a_sty, b_sty) {
365         (&ty::TyInfer(_), _) |
366         (_, &ty::TyInfer(_)) =>
367         {
368             // The caller should handle these cases!
369             bug!("var types encountered in super_relate_tys")
370         }
371
372         (&ty::TyError, _) | (_, &ty::TyError) =>
373         {
374             Ok(tcx.types.err)
375         }
376
377         (&ty::TyNever, _) |
378         (&ty::TyChar, _) |
379         (&ty::TyBool, _) |
380         (&ty::TyInt(_), _) |
381         (&ty::TyUint(_), _) |
382         (&ty::TyFloat(_), _) |
383         (&ty::TyStr, _)
384             if a == b =>
385         {
386             Ok(a)
387         }
388
389         (&ty::TyParam(ref a_p), &ty::TyParam(ref b_p))
390             if a_p.idx == b_p.idx =>
391         {
392             Ok(a)
393         }
394
395         (&ty::TyAdt(a_def, a_substs), &ty::TyAdt(b_def, b_substs))
396             if a_def == b_def =>
397         {
398             let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?;
399             Ok(tcx.mk_adt(a_def, substs))
400         }
401
402         (&ty::TyForeign(a_id), &ty::TyForeign(b_id))
403             if a_id == b_id =>
404         {
405             Ok(tcx.mk_foreign(a_id))
406         }
407
408         (&ty::TyDynamic(ref a_obj, ref a_region), &ty::TyDynamic(ref b_obj, ref b_region)) => {
409             let region_bound = relation.with_cause(Cause::ExistentialRegionBound,
410                                                        |relation| {
411                                                            relation.relate_with_variance(
412                                                                ty::Contravariant,
413                                                                a_region,
414                                                                b_region)
415                                                        })?;
416             Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound))
417         }
418
419         (&ty::TyGenerator(a_id, a_substs, a_interior),
420          &ty::TyGenerator(b_id, b_substs, b_interior))
421             if a_id == b_id =>
422         {
423             // All TyGenerator types with the same id represent
424             // the (anonymous) type of the same generator expression. So
425             // all of their regions should be equated.
426             let substs = relation.relate(&a_substs, &b_substs)?;
427             let interior = relation.relate(&a_interior, &b_interior)?;
428             Ok(tcx.mk_generator(a_id, substs, interior))
429         }
430
431         (&ty::TyGeneratorWitness(a_types), &ty::TyGeneratorWitness(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 = ty::Binder(GeneratorWitness(*a_types.skip_binder()));
436             let b_types = ty::Binder(GeneratorWitness(*b_types.skip_binder()));
437             // Then remove the GeneratorWitness for the result
438             let types = ty::Binder(relation.relate(&a_types, &b_types)?.skip_binder().0);
439             Ok(tcx.mk_generator_witness(types))
440         }
441
442         (&ty::TyClosure(a_id, a_substs),
443          &ty::TyClosure(b_id, b_substs))
444             if a_id == b_id =>
445         {
446             // All TyClosure 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_from_closure_substs(a_id, substs))
451         }
452
453         (&ty::TyRawPtr(ref a_mt), &ty::TyRawPtr(ref b_mt)) =>
454         {
455             let mt = relation.relate(a_mt, b_mt)?;
456             Ok(tcx.mk_ptr(mt))
457         }
458
459         (&ty::TyRef(a_r, ref a_mt), &ty::TyRef(b_r, ref b_mt)) =>
460         {
461             let r = relation.relate_with_variance(ty::Contravariant, &a_r, &b_r)?;
462             let mt = relation.relate(a_mt, b_mt)?;
463             Ok(tcx.mk_ref(r, mt))
464         }
465
466         (&ty::TyArray(a_t, sz_a), &ty::TyArray(b_t, sz_b)) =>
467         {
468             let t = relation.relate(&a_t, &b_t)?;
469             assert_eq!(sz_a.ty, tcx.types.usize);
470             assert_eq!(sz_b.ty, tcx.types.usize);
471             let to_u64 = |x: &'tcx ty::Const<'tcx>| -> Result<u64, ErrorReported> {
472                 match x.val {
473                     ConstVal::Value(Value::ByVal(prim)) => Ok(prim.to_u64().unwrap()),
474                     ConstVal::Unevaluated(def_id, substs) => {
475                         // FIXME(eddyb) get the right param_env.
476                         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
477                         match tcx.lift_to_global(&substs) {
478                             Some(substs) => {
479                                 let instance = ty::Instance::resolve(
480                                     tcx.global_tcx(),
481                                     param_env,
482                                     def_id,
483                                     substs,
484                                 );
485                                 if let Some(instance) = instance {
486                                     let cid = GlobalId {
487                                         instance,
488                                         promoted: None
489                                     };
490                                     match tcx.const_eval(param_env.and(cid)) {
491                                         Ok(&ty::Const {
492                                             val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(b))),
493                                             ..
494                                         }) => {
495                                             assert_eq!(b as u64 as u128, b);
496                                             return Ok(b as u64);
497                                         }
498                                         _ => {}
499                                     }
500                                 }
501                             },
502                             None => {}
503                         }
504                         tcx.sess.delay_span_bug(tcx.def_span(def_id),
505                             "array length could not be evaluated");
506                         Err(ErrorReported)
507                     }
508                     _ => bug!("arrays should not have {:?} as length", x)
509                 }
510             };
511             match (to_u64(sz_a), to_u64(sz_b)) {
512                 (Ok(sz_a_u64), Ok(sz_b_u64)) => {
513                     if sz_a_u64 == sz_b_u64 {
514                         Ok(tcx.mk_ty(ty::TyArray(t, sz_a)))
515                     } else {
516                         Err(TypeError::FixedArraySize(
517                             expected_found(relation, &sz_a_u64, &sz_b_u64)))
518                     }
519                 }
520                 // We reported an error or will ICE, so we can return TyError.
521                 (Err(ErrorReported), _) | (_, Err(ErrorReported)) => {
522                     Ok(tcx.types.err)
523                 }
524             }
525         }
526
527         (&ty::TySlice(a_t), &ty::TySlice(b_t)) =>
528         {
529             let t = relation.relate(&a_t, &b_t)?;
530             Ok(tcx.mk_slice(t))
531         }
532
533         (&ty::TyTuple(as_, a_defaulted), &ty::TyTuple(bs, b_defaulted)) =>
534         {
535             if as_.len() == bs.len() {
536                 let defaulted = a_defaulted || b_defaulted;
537                 Ok(tcx.mk_tup(as_.iter().zip(bs).map(|(a, b)| relation.relate(a, b)), defaulted)?)
538             } else if !(as_.is_empty() || bs.is_empty()) {
539                 Err(TypeError::TupleSize(
540                     expected_found(relation, &as_.len(), &bs.len())))
541             } else {
542                 Err(TypeError::Sorts(expected_found(relation, &a, &b)))
543             }
544         }
545
546         (&ty::TyFnDef(a_def_id, a_substs), &ty::TyFnDef(b_def_id, b_substs))
547             if a_def_id == b_def_id =>
548         {
549             let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?;
550             Ok(tcx.mk_fn_def(a_def_id, substs))
551         }
552
553         (&ty::TyFnPtr(a_fty), &ty::TyFnPtr(b_fty)) =>
554         {
555             let fty = relation.relate(&a_fty, &b_fty)?;
556             Ok(tcx.mk_fn_ptr(fty))
557         }
558
559         (&ty::TyProjection(ref a_data), &ty::TyProjection(ref b_data)) =>
560         {
561             let projection_ty = relation.relate(a_data, b_data)?;
562             Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs))
563         }
564
565         (&ty::TyAnon(a_def_id, a_substs), &ty::TyAnon(b_def_id, b_substs))
566             if a_def_id == b_def_id =>
567         {
568             let substs = relate_substs(relation, None, a_substs, b_substs)?;
569             Ok(tcx.mk_anon(a_def_id, substs))
570         }
571
572         _ =>
573         {
574             Err(TypeError::Sorts(expected_found(relation, &a, &b)))
575         }
576     }
577 }
578
579 impl<'tcx> Relate<'tcx> for &'tcx ty::Slice<ty::ExistentialPredicate<'tcx>> {
580     fn relate<'a, 'gcx, R>(relation: &mut R,
581                            a: &Self,
582                            b: &Self)
583         -> RelateResult<'tcx, Self>
584             where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a {
585
586         if a.len() != b.len() {
587             return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)));
588         }
589
590         let tcx = relation.tcx();
591         let v = a.iter().zip(b.iter()).map(|(ep_a, ep_b)| {
592             use ty::ExistentialPredicate::*;
593             match (*ep_a, *ep_b) {
594                 (Trait(ref a), Trait(ref b)) => Ok(Trait(relation.relate(a, b)?)),
595                 (Projection(ref a), Projection(ref b)) => Ok(Projection(relation.relate(a, b)?)),
596                 (AutoTrait(ref a), AutoTrait(ref b)) if a == b => Ok(AutoTrait(*a)),
597                 _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b)))
598             }
599         });
600         Ok(tcx.mk_existential_predicates(v)?)
601     }
602 }
603
604 impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> {
605     fn relate<'a, 'gcx, R>(relation: &mut R,
606                            a: &ty::ClosureSubsts<'tcx>,
607                            b: &ty::ClosureSubsts<'tcx>)
608                            -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>>
609         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
610     {
611         let substs = relate_substs(relation, None, a.substs, b.substs)?;
612         Ok(ty::ClosureSubsts { substs: substs })
613     }
614 }
615
616 impl<'tcx> Relate<'tcx> for ty::GeneratorInterior<'tcx> {
617     fn relate<'a, 'gcx, R>(relation: &mut R,
618                            a: &ty::GeneratorInterior<'tcx>,
619                            b: &ty::GeneratorInterior<'tcx>)
620                            -> RelateResult<'tcx, ty::GeneratorInterior<'tcx>>
621         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
622     {
623         assert_eq!(a.movable, b.movable);
624         let witness = relation.relate(&a.witness, &b.witness)?;
625         Ok(ty::GeneratorInterior { witness, movable: a.movable })
626     }
627 }
628
629 impl<'tcx> Relate<'tcx> for &'tcx Substs<'tcx> {
630     fn relate<'a, 'gcx, R>(relation: &mut R,
631                            a: &&'tcx Substs<'tcx>,
632                            b: &&'tcx Substs<'tcx>)
633                            -> RelateResult<'tcx, &'tcx Substs<'tcx>>
634         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
635     {
636         relate_substs(relation, None, a, b)
637     }
638 }
639
640 impl<'tcx> Relate<'tcx> for ty::Region<'tcx> {
641     fn relate<'a, 'gcx, R>(relation: &mut R,
642                            a: &ty::Region<'tcx>,
643                            b: &ty::Region<'tcx>)
644                            -> RelateResult<'tcx, ty::Region<'tcx>>
645         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
646     {
647         relation.regions(*a, *b)
648     }
649 }
650
651 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<T> {
652     fn relate<'a, 'gcx, R>(relation: &mut R,
653                            a: &ty::Binder<T>,
654                            b: &ty::Binder<T>)
655                            -> RelateResult<'tcx, ty::Binder<T>>
656         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
657     {
658         relation.binders(a, b)
659     }
660 }
661
662 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Rc<T> {
663     fn relate<'a, 'gcx, R>(relation: &mut R,
664                            a: &Rc<T>,
665                            b: &Rc<T>)
666                            -> RelateResult<'tcx, Rc<T>>
667         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
668     {
669         let a: &T = a;
670         let b: &T = b;
671         Ok(Rc::new(relation.relate(a, b)?))
672     }
673 }
674
675 impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for Box<T> {
676     fn relate<'a, 'gcx, R>(relation: &mut R,
677                            a: &Box<T>,
678                            b: &Box<T>)
679                            -> RelateResult<'tcx, Box<T>>
680         where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
681     {
682         let a: &T = a;
683         let b: &T = b;
684         Ok(Box::new(relation.relate(a, b)?))
685     }
686 }
687
688 impl<'tcx> Relate<'tcx> for Kind<'tcx> {
689     fn relate<'a, 'gcx, R>(
690         relation: &mut R,
691         a: &Kind<'tcx>,
692         b: &Kind<'tcx>
693     ) -> RelateResult<'tcx, Kind<'tcx>>
694     where
695         R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a,
696     {
697         match (a.unpack(), b.unpack()) {
698             (UnpackedKind::Lifetime(a_lt), UnpackedKind::Lifetime(b_lt)) => {
699                 Ok(relation.relate(&a_lt, &b_lt)?.into())
700             }
701             (UnpackedKind::Type(a_ty), UnpackedKind::Type(b_ty)) => {
702                 Ok(relation.relate(&a_ty, &b_ty)?.into())
703             }
704             (UnpackedKind::Lifetime(_), _) | (UnpackedKind::Type(_), _) => bug!()
705         }
706     }
707 }
708
709 ///////////////////////////////////////////////////////////////////////////
710 // Error handling
711
712 pub fn expected_found<'a, 'gcx, 'tcx, R, T>(relation: &mut R,
713                                             a: &T,
714                                             b: &T)
715                                             -> ExpectedFound<T>
716     where R: TypeRelation<'a, 'gcx, 'tcx>, T: Clone, 'gcx: 'a+'tcx, 'tcx: 'a
717 {
718     expected_found_bool(relation.a_is_expected(), a, b)
719 }
720
721 pub fn expected_found_bool<T>(a_is_expected: bool,
722                               a: &T,
723                               b: &T)
724                               -> ExpectedFound<T>
725     where T: Clone
726 {
727     let a = a.clone();
728     let b = b.clone();
729     if a_is_expected {
730         ExpectedFound {expected: a, found: b}
731     } else {
732         ExpectedFound {expected: b, found: a}
733     }
734 }