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