]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Update E0253.rs
[rust.git] / src / librustc / traits / mod.rs
1 // Copyright 2014 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 //! Trait Resolution. See README.md for an overview of how this works.
12
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
17
18 use hir::def_id::DefId;
19 use middle::free_region::FreeRegionMap;
20 use ty::subst;
21 use ty::{self, Ty, TyCtxt, TypeFoldable};
22 use infer::InferCtxt;
23
24 use std::rc::Rc;
25 use syntax::ast;
26 use syntax_pos::{Span, DUMMY_SP};
27
28 pub use self::error_reporting::TraitErrorKey;
29 pub use self::coherence::orphan_check;
30 pub use self::coherence::overlapping_impls;
31 pub use self::coherence::OrphanCheckErr;
32 pub use self::fulfill::{FulfillmentContext, GlobalFulfilledPredicates, RegionObligation};
33 pub use self::project::MismatchedProjectionTypes;
34 pub use self::project::{normalize, normalize_projection_type, Normalized};
35 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, ProjectionMode};
36 pub use self::object_safety::ObjectSafetyViolation;
37 pub use self::object_safety::MethodViolationCode;
38 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
39 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
40 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
41 pub use self::specialize::{OverlapError, specialization_graph, specializes, translate_substs};
42 pub use self::specialize::{SpecializesCache};
43 pub use self::util::elaborate_predicates;
44 pub use self::util::supertraits;
45 pub use self::util::Supertraits;
46 pub use self::util::supertrait_def_ids;
47 pub use self::util::SupertraitDefIds;
48 pub use self::util::transitive_bounds;
49
50 mod coherence;
51 mod error_reporting;
52 mod fulfill;
53 mod project;
54 mod object_safety;
55 mod select;
56 mod specialize;
57 mod structural_impls;
58 mod util;
59
60 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
61 /// which the vtable must be found.  The process of finding a vtable is
62 /// called "resolving" the `Obligation`. This process consists of
63 /// either identifying an `impl` (e.g., `impl Eq for int`) that
64 /// provides the required vtable, or else finding a bound that is in
65 /// scope. The eventual result is usually a `Selection` (defined below).
66 #[derive(Clone, PartialEq, Eq)]
67 pub struct Obligation<'tcx, T> {
68     pub cause: ObligationCause<'tcx>,
69     pub recursion_depth: usize,
70     pub predicate: T,
71 }
72
73 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
74 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
75
76 /// Why did we incur this obligation? Used for error reporting.
77 #[derive(Clone, Debug, PartialEq, Eq)]
78 pub struct ObligationCause<'tcx> {
79     pub span: Span,
80
81     // The id of the fn body that triggered this obligation. This is
82     // used for region obligations to determine the precise
83     // environment in which the region obligation should be evaluated
84     // (in particular, closures can add new assumptions). See the
85     // field `region_obligations` of the `FulfillmentContext` for more
86     // information.
87     pub body_id: ast::NodeId,
88
89     pub code: ObligationCauseCode<'tcx>
90 }
91
92 #[derive(Clone, Debug, PartialEq, Eq)]
93 pub enum ObligationCauseCode<'tcx> {
94     /// Not well classified or should be obvious from span.
95     MiscObligation,
96
97     /// A slice or array is WF only if `T: Sized`
98     SliceOrArrayElem,
99
100     /// A tuple is WF only if its middle elements are Sized
101     TupleElem,
102
103     /// This is the trait reference from the given projection
104     ProjectionWf(ty::ProjectionTy<'tcx>),
105
106     /// In an impl of trait X for type Y, type Y must
107     /// also implement all supertraits of X.
108     ItemObligation(DefId),
109
110     /// A type like `&'a T` is WF only if `T: 'a`.
111     ReferenceOutlivesReferent(Ty<'tcx>),
112
113     /// Obligation incurred due to an object cast.
114     ObjectCastObligation(/* Object type */ Ty<'tcx>),
115
116     /// Various cases where expressions must be sized/copy/etc:
117     AssignmentLhsSized,        // L = X implies that L is Sized
118     StructInitializerSized,    // S { ... } must be Sized
119     VariableType(ast::NodeId), // Type of each variable must be Sized
120     ReturnType,                // Return type must be Sized
121     RepeatVec,                 // [T,..n] --> T must be Copy
122
123     // Captures of variable the given id by a closure (span is the
124     // span of the closure)
125     ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
126
127     // Types of fields (other than the last) in a struct must be sized.
128     FieldSized,
129
130     // Constant expressions must be sized.
131     ConstSized,
132
133     // static items must have `Sync` type
134     SharedStatic,
135
136     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
137
138     ImplDerivedObligation(DerivedObligationCause<'tcx>),
139
140     CompareImplMethodObligation,
141 }
142
143 #[derive(Clone, Debug, PartialEq, Eq)]
144 pub struct DerivedObligationCause<'tcx> {
145     /// The trait reference of the parent obligation that led to the
146     /// current obligation. Note that only trait obligations lead to
147     /// derived obligations, so we just store the trait reference here
148     /// directly.
149     parent_trait_ref: ty::PolyTraitRef<'tcx>,
150
151     /// The parent trait had this cause
152     parent_code: Rc<ObligationCauseCode<'tcx>>
153 }
154
155 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
156 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
157 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
158
159 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
160
161 #[derive(Clone,Debug)]
162 pub enum SelectionError<'tcx> {
163     Unimplemented,
164     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
165                                 ty::PolyTraitRef<'tcx>,
166                                 ty::error::TypeError<'tcx>),
167     TraitNotObjectSafe(DefId),
168 }
169
170 pub struct FulfillmentError<'tcx> {
171     pub obligation: PredicateObligation<'tcx>,
172     pub code: FulfillmentErrorCode<'tcx>
173 }
174
175 #[derive(Clone)]
176 pub enum FulfillmentErrorCode<'tcx> {
177     CodeSelectionError(SelectionError<'tcx>),
178     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
179     CodeAmbiguity,
180 }
181
182 /// When performing resolution, it is typically the case that there
183 /// can be one of three outcomes:
184 ///
185 /// - `Ok(Some(r))`: success occurred with result `r`
186 /// - `Ok(None)`: could not definitely determine anything, usually due
187 ///   to inconclusive type inference.
188 /// - `Err(e)`: error `e` occurred
189 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
190
191 /// Given the successful resolution of an obligation, the `Vtable`
192 /// indicates where the vtable comes from. Note that while we call this
193 /// a "vtable", it does not necessarily indicate dynamic dispatch at
194 /// runtime. `Vtable` instances just tell the compiler where to find
195 /// methods, but in generic code those methods are typically statically
196 /// dispatched -- only when an object is constructed is a `Vtable`
197 /// instance reified into an actual vtable.
198 ///
199 /// For example, the vtable may be tied to a specific impl (case A),
200 /// or it may be relative to some bound that is in scope (case B).
201 ///
202 ///
203 /// ```
204 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
205 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
206 /// impl Clone for int { ... }             // Impl_3
207 ///
208 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
209 ///                 param: T,
210 ///                 mixed: Option<T>) {
211 ///
212 ///    // Case A: Vtable points at a specific impl. Only possible when
213 ///    // type is concretely known. If the impl itself has bounded
214 ///    // type parameters, Vtable will carry resolutions for those as well:
215 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
216 ///
217 ///    // Case B: Vtable must be provided by caller. This applies when
218 ///    // type is a type parameter.
219 ///    param.clone();    // VtableParam
220 ///
221 ///    // Case C: A mix of cases A and B.
222 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
223 /// }
224 /// ```
225 ///
226 /// ### The type parameter `N`
227 ///
228 /// See explanation on `VtableImplData`.
229 #[derive(Clone)]
230 pub enum Vtable<'tcx, N> {
231     /// Vtable identifying a particular impl.
232     VtableImpl(VtableImplData<'tcx, N>),
233
234     /// Vtable for default trait implementations
235     /// This carries the information and nested obligations with regards
236     /// to a default implementation for a trait `Trait`. The nested obligations
237     /// ensure the trait implementation holds for all the constituent types.
238     VtableDefaultImpl(VtableDefaultImplData<N>),
239
240     /// Successful resolution to an obligation provided by the caller
241     /// for some type parameter. The `Vec<N>` represents the
242     /// obligations incurred from normalizing the where-clause (if
243     /// any).
244     VtableParam(Vec<N>),
245
246     /// Virtual calls through an object
247     VtableObject(VtableObjectData<'tcx, N>),
248
249     /// Successful resolution for a builtin trait.
250     VtableBuiltin(VtableBuiltinData<N>),
251
252     /// Vtable automatically generated for a closure. The def ID is the ID
253     /// of the closure expression. This is a `VtableImpl` in spirit, but the
254     /// impl is generated by the compiler and does not appear in the source.
255     VtableClosure(VtableClosureData<'tcx, N>),
256
257     /// Same as above, but for a fn pointer type with the given signature.
258     VtableFnPointer(VtableFnPointerData<'tcx, N>),
259 }
260
261 /// Identifies a particular impl in the source, along with a set of
262 /// substitutions from the impl's type/lifetime parameters. The
263 /// `nested` vector corresponds to the nested obligations attached to
264 /// the impl's type parameters.
265 ///
266 /// The type parameter `N` indicates the type used for "nested
267 /// obligations" that are required by the impl. During type check, this
268 /// is `Obligation`, as one might expect. During trans, however, this
269 /// is `()`, because trans only requires a shallow resolution of an
270 /// impl, and nested obligations are satisfied later.
271 #[derive(Clone, PartialEq, Eq)]
272 pub struct VtableImplData<'tcx, N> {
273     pub impl_def_id: DefId,
274     pub substs: &'tcx subst::Substs<'tcx>,
275     pub nested: Vec<N>
276 }
277
278 #[derive(Clone, PartialEq, Eq)]
279 pub struct VtableClosureData<'tcx, N> {
280     pub closure_def_id: DefId,
281     pub substs: ty::ClosureSubsts<'tcx>,
282     /// Nested obligations. This can be non-empty if the closure
283     /// signature contains associated types.
284     pub nested: Vec<N>
285 }
286
287 #[derive(Clone)]
288 pub struct VtableDefaultImplData<N> {
289     pub trait_def_id: DefId,
290     pub nested: Vec<N>
291 }
292
293 #[derive(Clone)]
294 pub struct VtableBuiltinData<N> {
295     pub nested: Vec<N>
296 }
297
298 /// A vtable for some object-safe trait `Foo` automatically derived
299 /// for the object type `Foo`.
300 #[derive(PartialEq,Eq,Clone)]
301 pub struct VtableObjectData<'tcx, N> {
302     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
303     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
304
305     /// The vtable is formed by concatenating together the method lists of
306     /// the base object trait and all supertraits; this is the start of
307     /// `upcast_trait_ref`'s methods in that vtable.
308     pub vtable_base: usize,
309
310     pub nested: Vec<N>,
311 }
312
313 #[derive(Clone, PartialEq, Eq)]
314 pub struct VtableFnPointerData<'tcx, N> {
315     pub fn_ty: ty::Ty<'tcx>,
316     pub nested: Vec<N>
317 }
318
319 /// Creates predicate obligations from the generic bounds.
320 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
321                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
322                                      -> PredicateObligations<'tcx>
323 {
324     util::predicates_for_generics(cause, 0, generic_bounds)
325 }
326
327 /// Determines whether the type `ty` is known to meet `bound` and
328 /// returns true if so. Returns false if `ty` either does not meet
329 /// `bound` or is not known to meet bound (note that this is
330 /// conservative towards *no impl*, which is the opposite of the
331 /// `evaluate` methods).
332 pub fn type_known_to_meet_builtin_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
333                                                         ty: Ty<'tcx>,
334                                                         bound: ty::BuiltinBound,
335                                                         span: Span)
336                                                         -> bool
337 {
338     debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})",
339            ty,
340            bound);
341
342     let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
343     let obligation =
344         infcx.tcx.predicate_for_builtin_bound(cause, bound, 0, ty);
345     let obligation = match obligation {
346         Ok(o) => o,
347         Err(..) => return false
348     };
349     let result = SelectionContext::new(infcx)
350         .evaluate_obligation_conservatively(&obligation);
351     debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} => {:?}",
352            ty, bound, result);
353
354     if result && (ty.has_infer_types() || ty.has_closure_types()) {
355         // Because of inference "guessing", selection can sometimes claim
356         // to succeed while the success requires a guess. To ensure
357         // this function's result remains infallible, we must confirm
358         // that guess. While imperfect, I believe this is sound.
359
360         let mut fulfill_cx = FulfillmentContext::new();
361
362         // We can use a dummy node-id here because we won't pay any mind
363         // to region obligations that arise (there shouldn't really be any
364         // anyhow).
365         let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
366
367         fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
368
369         // Note: we only assume something is `Copy` if we can
370         // *definitively* show that it implements `Copy`. Otherwise,
371         // assume it is move; linear is always ok.
372         match fulfill_cx.select_all_or_error(infcx) {
373             Ok(()) => {
374                 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success",
375                        ty,
376                        bound);
377                 true
378             }
379             Err(e) => {
380                 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}",
381                        ty,
382                        bound,
383                        e);
384                 false
385             }
386         }
387     } else {
388         result
389     }
390 }
391
392 // FIXME: this is gonna need to be removed ...
393 /// Normalizes the parameter environment, reporting errors if they occur.
394 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
395     unnormalized_env: ty::ParameterEnvironment<'tcx>,
396     cause: ObligationCause<'tcx>)
397     -> ty::ParameterEnvironment<'tcx>
398 {
399     // I'm not wild about reporting errors here; I'd prefer to
400     // have the errors get reported at a defined place (e.g.,
401     // during typeck). Instead I have all parameter
402     // environments, in effect, going through this function
403     // and hence potentially reporting errors. This ensurse of
404     // course that we never forget to normalize (the
405     // alternative seemed like it would involve a lot of
406     // manual invocations of this fn -- and then we'd have to
407     // deal with the errors at each of those sites).
408     //
409     // In any case, in practice, typeck constructs all the
410     // parameter environments once for every fn as it goes,
411     // and errors will get reported then; so after typeck we
412     // can be sure that no errors should occur.
413
414     let span = cause.span;
415     let body_id = cause.body_id;
416
417     debug!("normalize_param_env_or_error(unnormalized_env={:?})",
418            unnormalized_env);
419
420     let predicates: Vec<_> =
421         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
422         .filter(|p| !p.is_global()) // (*)
423         .collect();
424
425     // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
426     // need to be in the *environment* to be proven, so screen those
427     // out. This is important for the soundness of inter-fn
428     // caching. Note though that we should probably check that these
429     // predicates hold at the point where the environment is
430     // constructed, but I am not currently doing so out of laziness.
431     // -nmatsakis
432
433     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
434            predicates);
435
436     let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
437
438     tcx.infer_ctxt(None, Some(elaborated_env), ProjectionMode::AnyFinal).enter(|infcx| {
439         let predicates = match fully_normalize(&infcx, cause,
440                                                &infcx.parameter_environment.caller_bounds) {
441             Ok(predicates) => predicates,
442             Err(errors) => {
443                 infcx.report_fulfillment_errors(&errors);
444                 // An unnormalized env is better than nothing.
445                 return infcx.parameter_environment;
446             }
447         };
448
449         debug!("normalize_param_env_or_error: normalized predicates={:?}",
450             predicates);
451
452         let free_regions = FreeRegionMap::new();
453         infcx.resolve_regions_and_report_errors(&free_regions, body_id);
454         let predicates = match infcx.fully_resolve(&predicates) {
455             Ok(predicates) => predicates,
456             Err(fixup_err) => {
457                 // If we encounter a fixup error, it means that some type
458                 // variable wound up unconstrained. I actually don't know
459                 // if this can happen, and I certainly don't expect it to
460                 // happen often, but if it did happen it probably
461                 // represents a legitimate failure due to some kind of
462                 // unconstrained variable, and it seems better not to ICE,
463                 // all things considered.
464                 tcx.sess.span_err(span, &fixup_err.to_string());
465                 // An unnormalized env is better than nothing.
466                 return infcx.parameter_environment;
467             }
468         };
469
470         let predicates = match tcx.lift_to_global(&predicates) {
471             Some(predicates) => predicates,
472             None => return infcx.parameter_environment
473         };
474
475         debug!("normalize_param_env_or_error: resolved predicates={:?}",
476             predicates);
477
478         infcx.parameter_environment.with_caller_bounds(predicates)
479     })
480 }
481
482 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
483                                           cause: ObligationCause<'tcx>,
484                                           value: &T)
485                                           -> Result<T, Vec<FulfillmentError<'tcx>>>
486     where T : TypeFoldable<'tcx>
487 {
488     debug!("fully_normalize(value={:?})", value);
489
490     let mut selcx = &mut SelectionContext::new(infcx);
491     // FIXME (@jroesch) ISSUE 26721
492     // I'm not sure if this is a bug or not, needs further investigation.
493     // It appears that by reusing the fulfillment_cx here we incur more
494     // obligations and later trip an asssertion on regionck.rs line 337.
495     //
496     // The two possibilities I see is:
497     //      - normalization is not actually fully happening and we
498     //        have a bug else where
499     //      - we are adding a duplicate bound into the list causing
500     //        its size to change.
501     //
502     // I think we should probably land this refactor and then come
503     // back to this is a follow-up patch.
504     let mut fulfill_cx = FulfillmentContext::new();
505
506     let Normalized { value: normalized_value, obligations } =
507         project::normalize(selcx, cause, value);
508     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
509            normalized_value,
510            obligations);
511     for obligation in obligations {
512         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
513     }
514
515     debug!("fully_normalize: select_all_or_error start");
516     match fulfill_cx.select_all_or_error(infcx) {
517         Ok(()) => { }
518         Err(e) => {
519             debug!("fully_normalize: error={:?}", e);
520             return Err(e);
521         }
522     }
523     debug!("fully_normalize: select_all_or_error complete");
524     let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
525     debug!("fully_normalize: resolved_value={:?}", resolved_value);
526     Ok(resolved_value)
527 }
528
529 impl<'tcx,O> Obligation<'tcx,O> {
530     pub fn new(cause: ObligationCause<'tcx>,
531                trait_ref: O)
532                -> Obligation<'tcx, O>
533     {
534         Obligation { cause: cause,
535                      recursion_depth: 0,
536                      predicate: trait_ref }
537     }
538
539     fn with_depth(cause: ObligationCause<'tcx>,
540                   recursion_depth: usize,
541                   trait_ref: O)
542                   -> Obligation<'tcx, O>
543     {
544         Obligation { cause: cause,
545                      recursion_depth: recursion_depth,
546                      predicate: trait_ref }
547     }
548
549     pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
550         Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
551     }
552
553     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
554         Obligation { cause: self.cause.clone(),
555                      recursion_depth: self.recursion_depth,
556                      predicate: value }
557     }
558 }
559
560 impl<'tcx> ObligationCause<'tcx> {
561     pub fn new(span: Span,
562                body_id: ast::NodeId,
563                code: ObligationCauseCode<'tcx>)
564                -> ObligationCause<'tcx> {
565         ObligationCause { span: span, body_id: body_id, code: code }
566     }
567
568     pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
569         ObligationCause { span: span, body_id: body_id, code: MiscObligation }
570     }
571
572     pub fn dummy() -> ObligationCause<'tcx> {
573         ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
574     }
575 }
576
577 impl<'tcx, N> Vtable<'tcx, N> {
578     pub fn nested_obligations(self) -> Vec<N> {
579         match self {
580             VtableImpl(i) => i.nested,
581             VtableParam(n) => n,
582             VtableBuiltin(i) => i.nested,
583             VtableDefaultImpl(d) => d.nested,
584             VtableClosure(c) => c.nested,
585             VtableObject(d) => d.nested,
586             VtableFnPointer(d) => d.nested,
587         }
588     }
589
590     fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
591         match self {
592             &mut VtableImpl(ref mut i) => &mut i.nested,
593             &mut VtableParam(ref mut n) => n,
594             &mut VtableBuiltin(ref mut i) => &mut i.nested,
595             &mut VtableDefaultImpl(ref mut d) => &mut d.nested,
596             &mut VtableClosure(ref mut c) => &mut c.nested,
597             &mut VtableObject(ref mut d) => &mut d.nested,
598             &mut VtableFnPointer(ref mut d) => &mut d.nested,
599         }
600     }
601
602     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
603         match self {
604             VtableImpl(i) => VtableImpl(VtableImplData {
605                 impl_def_id: i.impl_def_id,
606                 substs: i.substs,
607                 nested: i.nested.into_iter().map(f).collect(),
608             }),
609             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
610             VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
611                 nested: i.nested.into_iter().map(f).collect(),
612             }),
613             VtableObject(o) => VtableObject(VtableObjectData {
614                 upcast_trait_ref: o.upcast_trait_ref,
615                 vtable_base: o.vtable_base,
616                 nested: o.nested.into_iter().map(f).collect(),
617             }),
618             VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
619                 trait_def_id: d.trait_def_id,
620                 nested: d.nested.into_iter().map(f).collect(),
621             }),
622             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
623                 fn_ty: p.fn_ty,
624                 nested: p.nested.into_iter().map(f).collect(),
625             }),
626             VtableClosure(c) => VtableClosure(VtableClosureData {
627                 closure_def_id: c.closure_def_id,
628                 substs: c.substs,
629                 nested: c.nested.into_iter().map(f).collect(),
630             })
631         }
632     }
633 }
634
635 impl<'tcx> FulfillmentError<'tcx> {
636     fn new(obligation: PredicateObligation<'tcx>,
637            code: FulfillmentErrorCode<'tcx>)
638            -> FulfillmentError<'tcx>
639     {
640         FulfillmentError { obligation: obligation, code: code }
641     }
642 }
643
644 impl<'tcx> TraitObligation<'tcx> {
645     fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
646         ty::Binder(self.predicate.skip_binder().self_ty())
647     }
648 }