]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Auto merge of #41157 - aidanhs:aphs-debug-appveyor-cache, r=TimNN
[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;
19 use hir::def_id::DefId;
20 use middle::free_region::FreeRegionMap;
21 use ty::subst::Substs;
22 use ty::{self, Ty, TyCtxt, TypeFoldable, ToPredicate};
23 use ty::error::{ExpectedFound, TypeError};
24 use infer::{InferCtxt};
25
26 use std::rc::Rc;
27 use syntax::ast;
28 use syntax_pos::{Span, DUMMY_SP};
29
30 pub use self::error_reporting::TraitErrorKey;
31 pub use self::coherence::orphan_check;
32 pub use self::coherence::overlapping_impls;
33 pub use self::coherence::OrphanCheckErr;
34 pub use self::fulfill::{FulfillmentContext, GlobalFulfilledPredicates, RegionObligation};
35 pub use self::project::MismatchedProjectionTypes;
36 pub use self::project::{normalize, normalize_projection_type, Normalized};
37 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal};
38 pub use self::object_safety::ObjectSafetyViolation;
39 pub use self::object_safety::MethodViolationCode;
40 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
41 pub use self::specialize::{OverlapError, specialization_graph, specializes, translate_substs};
42 pub use self::specialize::{SpecializesCache, find_associated_item};
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     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
114     ObjectTypeBound(Ty<'tcx>, &'tcx ty::Region),
115
116     /// Obligation incurred due to an object cast.
117     ObjectCastObligation(/* Object type */ Ty<'tcx>),
118
119     /// Various cases where expressions must be sized/copy/etc:
120     AssignmentLhsSized,        // L = X implies that L is Sized
121     StructInitializerSized,    // S { ... } must be Sized
122     VariableType(ast::NodeId), // Type of each variable must be Sized
123     ReturnType,                // Return type must be Sized
124     RepeatVec,                 // [T,..n] --> T must be Copy
125
126     // Types of fields (other than the last) in a struct must be sized.
127     FieldSized,
128
129     // Constant expressions must be sized.
130     ConstSized,
131
132     // static items must have `Sync` type
133     SharedStatic,
134
135     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
136
137     ImplDerivedObligation(DerivedObligationCause<'tcx>),
138
139     // error derived when matching traits/impls; see ObligationCause for more details
140     CompareImplMethodObligation {
141         item_name: ast::Name,
142         impl_item_def_id: DefId,
143         trait_item_def_id: DefId,
144         lint_id: Option<ast::NodeId>,
145     },
146
147     // Checking that this expression can be assigned where it needs to be
148     // FIXME(eddyb) #11161 is the original Expr required?
149     ExprAssignable,
150
151     // Computing common supertype in the arms of a match expression
152     MatchExpressionArm { arm_span: Span,
153                          source: hir::MatchSource },
154
155     // Computing common supertype in an if expression
156     IfExpression,
157
158     // Computing common supertype of an if expression with no else counter-part
159     IfExpressionWithNoElse,
160
161     // `where a == b`
162     EquatePredicate,
163
164     // `main` has wrong type
165     MainFunctionType,
166
167     // `start` has wrong type
168     StartFunctionType,
169
170     // intrinsic has wrong type
171     IntrinsicType,
172
173     // method receiver
174     MethodReceiver,
175
176     // `return` with no expression
177     ReturnNoExpression,
178 }
179
180 #[derive(Clone, Debug, PartialEq, Eq)]
181 pub struct DerivedObligationCause<'tcx> {
182     /// The trait reference of the parent obligation that led to the
183     /// current obligation. Note that only trait obligations lead to
184     /// derived obligations, so we just store the trait reference here
185     /// directly.
186     parent_trait_ref: ty::PolyTraitRef<'tcx>,
187
188     /// The parent trait had this cause
189     parent_code: Rc<ObligationCauseCode<'tcx>>
190 }
191
192 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
193 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
194 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
195
196 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
197
198 #[derive(Clone,Debug)]
199 pub enum SelectionError<'tcx> {
200     Unimplemented,
201     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
202                                 ty::PolyTraitRef<'tcx>,
203                                 ty::error::TypeError<'tcx>),
204     TraitNotObjectSafe(DefId),
205 }
206
207 pub struct FulfillmentError<'tcx> {
208     pub obligation: PredicateObligation<'tcx>,
209     pub code: FulfillmentErrorCode<'tcx>
210 }
211
212 #[derive(Clone)]
213 pub enum FulfillmentErrorCode<'tcx> {
214     CodeSelectionError(SelectionError<'tcx>),
215     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
216     CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
217                      TypeError<'tcx>), // always comes from a SubtypePredicate
218     CodeAmbiguity,
219 }
220
221 /// When performing resolution, it is typically the case that there
222 /// can be one of three outcomes:
223 ///
224 /// - `Ok(Some(r))`: success occurred with result `r`
225 /// - `Ok(None)`: could not definitely determine anything, usually due
226 ///   to inconclusive type inference.
227 /// - `Err(e)`: error `e` occurred
228 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
229
230 /// Given the successful resolution of an obligation, the `Vtable`
231 /// indicates where the vtable comes from. Note that while we call this
232 /// a "vtable", it does not necessarily indicate dynamic dispatch at
233 /// runtime. `Vtable` instances just tell the compiler where to find
234 /// methods, but in generic code those methods are typically statically
235 /// dispatched -- only when an object is constructed is a `Vtable`
236 /// instance reified into an actual vtable.
237 ///
238 /// For example, the vtable may be tied to a specific impl (case A),
239 /// or it may be relative to some bound that is in scope (case B).
240 ///
241 ///
242 /// ```
243 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
244 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
245 /// impl Clone for int { ... }             // Impl_3
246 ///
247 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
248 ///                 param: T,
249 ///                 mixed: Option<T>) {
250 ///
251 ///    // Case A: Vtable points at a specific impl. Only possible when
252 ///    // type is concretely known. If the impl itself has bounded
253 ///    // type parameters, Vtable will carry resolutions for those as well:
254 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
255 ///
256 ///    // Case B: Vtable must be provided by caller. This applies when
257 ///    // type is a type parameter.
258 ///    param.clone();    // VtableParam
259 ///
260 ///    // Case C: A mix of cases A and B.
261 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
262 /// }
263 /// ```
264 ///
265 /// ### The type parameter `N`
266 ///
267 /// See explanation on `VtableImplData`.
268 #[derive(Clone)]
269 pub enum Vtable<'tcx, N> {
270     /// Vtable identifying a particular impl.
271     VtableImpl(VtableImplData<'tcx, N>),
272
273     /// Vtable for default trait implementations
274     /// This carries the information and nested obligations with regards
275     /// to a default implementation for a trait `Trait`. The nested obligations
276     /// ensure the trait implementation holds for all the constituent types.
277     VtableDefaultImpl(VtableDefaultImplData<N>),
278
279     /// Successful resolution to an obligation provided by the caller
280     /// for some type parameter. The `Vec<N>` represents the
281     /// obligations incurred from normalizing the where-clause (if
282     /// any).
283     VtableParam(Vec<N>),
284
285     /// Virtual calls through an object
286     VtableObject(VtableObjectData<'tcx, N>),
287
288     /// Successful resolution for a builtin trait.
289     VtableBuiltin(VtableBuiltinData<N>),
290
291     /// Vtable automatically generated for a closure. The def ID is the ID
292     /// of the closure expression. This is a `VtableImpl` in spirit, but the
293     /// impl is generated by the compiler and does not appear in the source.
294     VtableClosure(VtableClosureData<'tcx, N>),
295
296     /// Same as above, but for a fn pointer type with the given signature.
297     VtableFnPointer(VtableFnPointerData<'tcx, N>),
298 }
299
300 /// Identifies a particular impl in the source, along with a set of
301 /// substitutions from the impl's type/lifetime parameters. The
302 /// `nested` vector corresponds to the nested obligations attached to
303 /// the impl's type parameters.
304 ///
305 /// The type parameter `N` indicates the type used for "nested
306 /// obligations" that are required by the impl. During type check, this
307 /// is `Obligation`, as one might expect. During trans, however, this
308 /// is `()`, because trans only requires a shallow resolution of an
309 /// impl, and nested obligations are satisfied later.
310 #[derive(Clone, PartialEq, Eq)]
311 pub struct VtableImplData<'tcx, N> {
312     pub impl_def_id: DefId,
313     pub substs: &'tcx Substs<'tcx>,
314     pub nested: Vec<N>
315 }
316
317 #[derive(Clone, PartialEq, Eq)]
318 pub struct VtableClosureData<'tcx, N> {
319     pub closure_def_id: DefId,
320     pub substs: ty::ClosureSubsts<'tcx>,
321     /// Nested obligations. This can be non-empty if the closure
322     /// signature contains associated types.
323     pub nested: Vec<N>
324 }
325
326 #[derive(Clone)]
327 pub struct VtableDefaultImplData<N> {
328     pub trait_def_id: DefId,
329     pub nested: Vec<N>
330 }
331
332 #[derive(Clone)]
333 pub struct VtableBuiltinData<N> {
334     pub nested: Vec<N>
335 }
336
337 /// A vtable for some object-safe trait `Foo` automatically derived
338 /// for the object type `Foo`.
339 #[derive(PartialEq,Eq,Clone)]
340 pub struct VtableObjectData<'tcx, N> {
341     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
342     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
343
344     /// The vtable is formed by concatenating together the method lists of
345     /// the base object trait and all supertraits; this is the start of
346     /// `upcast_trait_ref`'s methods in that vtable.
347     pub vtable_base: usize,
348
349     pub nested: Vec<N>,
350 }
351
352 #[derive(Clone, PartialEq, Eq)]
353 pub struct VtableFnPointerData<'tcx, N> {
354     pub fn_ty: ty::Ty<'tcx>,
355     pub nested: Vec<N>
356 }
357
358 /// Creates predicate obligations from the generic bounds.
359 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
360                                      generic_bounds: &ty::InstantiatedPredicates<'tcx>)
361                                      -> PredicateObligations<'tcx>
362 {
363     util::predicates_for_generics(cause, 0, generic_bounds)
364 }
365
366 /// Determines whether the type `ty` is known to meet `bound` and
367 /// returns true if so. Returns false if `ty` either does not meet
368 /// `bound` or is not known to meet bound (note that this is
369 /// conservative towards *no impl*, which is the opposite of the
370 /// `evaluate` methods).
371 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
372                                                 ty: Ty<'tcx>,
373                                                 def_id: DefId,
374                                                 span: Span)
375 -> bool
376 {
377     debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
378            ty,
379            infcx.tcx.item_path_str(def_id));
380
381     let trait_ref = ty::TraitRef {
382         def_id: def_id,
383         substs: infcx.tcx.mk_substs_trait(ty, &[]),
384     };
385     let obligation = Obligation {
386         cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
387         recursion_depth: 0,
388         predicate: trait_ref.to_predicate(),
389     };
390
391     let result = SelectionContext::new(infcx)
392         .evaluate_obligation_conservatively(&obligation);
393     debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
394            ty, infcx.tcx.item_path_str(def_id), result);
395
396     if result && (ty.has_infer_types() || ty.has_closure_types()) {
397         // Because of inference "guessing", selection can sometimes claim
398         // to succeed while the success requires a guess. To ensure
399         // this function's result remains infallible, we must confirm
400         // that guess. While imperfect, I believe this is sound.
401
402         let mut fulfill_cx = FulfillmentContext::new();
403
404         // We can use a dummy node-id here because we won't pay any mind
405         // to region obligations that arise (there shouldn't really be any
406         // anyhow).
407         let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
408
409         fulfill_cx.register_bound(infcx, ty, def_id, cause);
410
411         // Note: we only assume something is `Copy` if we can
412         // *definitively* show that it implements `Copy`. Otherwise,
413         // assume it is move; linear is always ok.
414         match fulfill_cx.select_all_or_error(infcx) {
415             Ok(()) => {
416                 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
417                        ty,
418                        infcx.tcx.item_path_str(def_id));
419                 true
420             }
421             Err(e) => {
422                 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
423                        ty,
424                        infcx.tcx.item_path_str(def_id),
425                        e);
426                 false
427             }
428         }
429     } else {
430         result
431     }
432 }
433
434 // FIXME: this is gonna need to be removed ...
435 /// Normalizes the parameter environment, reporting errors if they occur.
436 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
437     unnormalized_env: ty::ParameterEnvironment<'tcx>,
438     cause: ObligationCause<'tcx>)
439     -> ty::ParameterEnvironment<'tcx>
440 {
441     // I'm not wild about reporting errors here; I'd prefer to
442     // have the errors get reported at a defined place (e.g.,
443     // during typeck). Instead I have all parameter
444     // environments, in effect, going through this function
445     // and hence potentially reporting errors. This ensurse of
446     // course that we never forget to normalize (the
447     // alternative seemed like it would involve a lot of
448     // manual invocations of this fn -- and then we'd have to
449     // deal with the errors at each of those sites).
450     //
451     // In any case, in practice, typeck constructs all the
452     // parameter environments once for every fn as it goes,
453     // and errors will get reported then; so after typeck we
454     // can be sure that no errors should occur.
455
456     let span = cause.span;
457     let body_id = cause.body_id;
458
459     debug!("normalize_param_env_or_error(unnormalized_env={:?})",
460            unnormalized_env);
461
462     let predicates: Vec<_> =
463         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
464         .filter(|p| !p.is_global()) // (*)
465         .collect();
466
467     // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
468     // need to be in the *environment* to be proven, so screen those
469     // out. This is important for the soundness of inter-fn
470     // caching. Note though that we should probably check that these
471     // predicates hold at the point where the environment is
472     // constructed, but I am not currently doing so out of laziness.
473     // -nmatsakis
474
475     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
476            predicates);
477
478     let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
479
480     tcx.infer_ctxt(elaborated_env, Reveal::UserFacing).enter(|infcx| {
481         let predicates = match fully_normalize(&infcx, cause,
482                                                &infcx.parameter_environment.caller_bounds) {
483             Ok(predicates) => predicates,
484             Err(errors) => {
485                 infcx.report_fulfillment_errors(&errors);
486                 // An unnormalized env is better than nothing.
487                 return infcx.parameter_environment;
488             }
489         };
490
491         debug!("normalize_param_env_or_error: normalized predicates={:?}",
492             predicates);
493
494         let free_regions = FreeRegionMap::new();
495         infcx.resolve_regions_and_report_errors(&free_regions, body_id);
496         let predicates = match infcx.fully_resolve(&predicates) {
497             Ok(predicates) => predicates,
498             Err(fixup_err) => {
499                 // If we encounter a fixup error, it means that some type
500                 // variable wound up unconstrained. I actually don't know
501                 // if this can happen, and I certainly don't expect it to
502                 // happen often, but if it did happen it probably
503                 // represents a legitimate failure due to some kind of
504                 // unconstrained variable, and it seems better not to ICE,
505                 // all things considered.
506                 tcx.sess.span_err(span, &fixup_err.to_string());
507                 // An unnormalized env is better than nothing.
508                 return infcx.parameter_environment;
509             }
510         };
511
512         let predicates = match tcx.lift_to_global(&predicates) {
513             Some(predicates) => predicates,
514             None => return infcx.parameter_environment
515         };
516
517         debug!("normalize_param_env_or_error: resolved predicates={:?}",
518             predicates);
519
520         infcx.parameter_environment.with_caller_bounds(predicates)
521     })
522 }
523
524 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
525                                           cause: ObligationCause<'tcx>,
526                                           value: &T)
527                                           -> Result<T, Vec<FulfillmentError<'tcx>>>
528     where T : TypeFoldable<'tcx>
529 {
530     debug!("fully_normalize(value={:?})", value);
531
532     let mut selcx = &mut SelectionContext::new(infcx);
533     // FIXME (@jroesch) ISSUE 26721
534     // I'm not sure if this is a bug or not, needs further investigation.
535     // It appears that by reusing the fulfillment_cx here we incur more
536     // obligations and later trip an asssertion on regionck.rs line 337.
537     //
538     // The two possibilities I see is:
539     //      - normalization is not actually fully happening and we
540     //        have a bug else where
541     //      - we are adding a duplicate bound into the list causing
542     //        its size to change.
543     //
544     // I think we should probably land this refactor and then come
545     // back to this is a follow-up patch.
546     let mut fulfill_cx = FulfillmentContext::new();
547
548     let Normalized { value: normalized_value, obligations } =
549         project::normalize(selcx, cause, value);
550     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
551            normalized_value,
552            obligations);
553     for obligation in obligations {
554         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
555     }
556
557     debug!("fully_normalize: select_all_or_error start");
558     match fulfill_cx.select_all_or_error(infcx) {
559         Ok(()) => { }
560         Err(e) => {
561             debug!("fully_normalize: error={:?}", e);
562             return Err(e);
563         }
564     }
565     debug!("fully_normalize: select_all_or_error complete");
566     let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
567     debug!("fully_normalize: resolved_value={:?}", resolved_value);
568     Ok(resolved_value)
569 }
570
571 /// Normalizes the predicates and checks whether they hold.  If this
572 /// returns false, then either normalize encountered an error or one
573 /// of the predicates did not hold. Used when creating vtables to
574 /// check for unsatisfiable methods.
575 pub fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
576                                                predicates: Vec<ty::Predicate<'tcx>>)
577                                                -> bool
578 {
579     debug!("normalize_and_test_predicates(predicates={:?})",
580            predicates);
581
582     tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
583         let mut selcx = SelectionContext::new(&infcx);
584         let mut fulfill_cx = FulfillmentContext::new();
585         let cause = ObligationCause::dummy();
586         let Normalized { value: predicates, obligations } =
587             normalize(&mut selcx, cause.clone(), &predicates);
588         for obligation in obligations {
589             fulfill_cx.register_predicate_obligation(&infcx, obligation);
590         }
591         for predicate in predicates {
592             let obligation = Obligation::new(cause.clone(), predicate);
593             fulfill_cx.register_predicate_obligation(&infcx, obligation);
594         }
595
596         fulfill_cx.select_all_or_error(&infcx).is_ok()
597     })
598 }
599
600 /// Given a trait `trait_ref`, iterates the vtable entries
601 /// that come from `trait_ref`, including its supertraits.
602 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
603 pub fn get_vtable_methods<'a, 'tcx>(
604     tcx: TyCtxt<'a, 'tcx, 'tcx>,
605     trait_ref: ty::PolyTraitRef<'tcx>)
606     -> impl Iterator<Item=Option<(DefId, &'tcx Substs<'tcx>)>> + 'a
607 {
608     debug!("get_vtable_methods({:?})", trait_ref);
609
610     supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
611         tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id());
612
613         let trait_methods = tcx.associated_items(trait_ref.def_id())
614             .filter(|item| item.kind == ty::AssociatedKind::Method);
615
616         // Now list each method's DefId and Substs (for within its trait).
617         // If the method can never be called from this object, produce None.
618         trait_methods.map(move |trait_method| {
619             debug!("get_vtable_methods: trait_method={:?}", trait_method);
620             let def_id = trait_method.def_id;
621
622             // Some methods cannot be called on an object; skip those.
623             if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
624                 debug!("get_vtable_methods: not vtable safe");
625                 return None;
626             }
627
628             // the method may have some early-bound lifetimes, add
629             // regions for those
630             let substs = Substs::for_item(tcx, def_id,
631                                           |_, _| tcx.mk_region(ty::ReErased),
632                                           |def, _| trait_ref.substs().type_for_def(def));
633
634             // the trait type may have higher-ranked lifetimes in it;
635             // so erase them if they appear, so that we get the type
636             // at some particular call site
637             let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
638
639             // It's possible that the method relies on where clauses that
640             // do not hold for this particular set of type parameters.
641             // Note that this method could then never be called, so we
642             // do not want to try and trans it, in that case (see #23435).
643             let predicates = tcx.item_predicates(def_id).instantiate_own(tcx, substs);
644             if !normalize_and_test_predicates(tcx, predicates.predicates) {
645                 debug!("get_vtable_methods: predicates do not hold");
646                 return None;
647             }
648
649             Some((def_id, substs))
650         })
651     })
652 }
653
654 impl<'tcx,O> Obligation<'tcx,O> {
655     pub fn new(cause: ObligationCause<'tcx>,
656                trait_ref: O)
657                -> Obligation<'tcx, O>
658     {
659         Obligation { cause: cause,
660                      recursion_depth: 0,
661                      predicate: trait_ref }
662     }
663
664     fn with_depth(cause: ObligationCause<'tcx>,
665                   recursion_depth: usize,
666                   trait_ref: O)
667                   -> Obligation<'tcx, O>
668     {
669         Obligation { cause: cause,
670                      recursion_depth: recursion_depth,
671                      predicate: trait_ref }
672     }
673
674     pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
675         Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
676     }
677
678     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
679         Obligation { cause: self.cause.clone(),
680                      recursion_depth: self.recursion_depth,
681                      predicate: value }
682     }
683 }
684
685 impl<'tcx> ObligationCause<'tcx> {
686     pub fn new(span: Span,
687                body_id: ast::NodeId,
688                code: ObligationCauseCode<'tcx>)
689                -> ObligationCause<'tcx> {
690         ObligationCause { span: span, body_id: body_id, code: code }
691     }
692
693     pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
694         ObligationCause { span: span, body_id: body_id, code: MiscObligation }
695     }
696
697     pub fn dummy() -> ObligationCause<'tcx> {
698         ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
699     }
700 }
701
702 impl<'tcx, N> Vtable<'tcx, N> {
703     pub fn nested_obligations(self) -> Vec<N> {
704         match self {
705             VtableImpl(i) => i.nested,
706             VtableParam(n) => n,
707             VtableBuiltin(i) => i.nested,
708             VtableDefaultImpl(d) => d.nested,
709             VtableClosure(c) => c.nested,
710             VtableObject(d) => d.nested,
711             VtableFnPointer(d) => d.nested,
712         }
713     }
714
715     fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
716         match self {
717             &mut VtableImpl(ref mut i) => &mut i.nested,
718             &mut VtableParam(ref mut n) => n,
719             &mut VtableBuiltin(ref mut i) => &mut i.nested,
720             &mut VtableDefaultImpl(ref mut d) => &mut d.nested,
721             &mut VtableClosure(ref mut c) => &mut c.nested,
722             &mut VtableObject(ref mut d) => &mut d.nested,
723             &mut VtableFnPointer(ref mut d) => &mut d.nested,
724         }
725     }
726
727     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
728         match self {
729             VtableImpl(i) => VtableImpl(VtableImplData {
730                 impl_def_id: i.impl_def_id,
731                 substs: i.substs,
732                 nested: i.nested.into_iter().map(f).collect(),
733             }),
734             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
735             VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
736                 nested: i.nested.into_iter().map(f).collect(),
737             }),
738             VtableObject(o) => VtableObject(VtableObjectData {
739                 upcast_trait_ref: o.upcast_trait_ref,
740                 vtable_base: o.vtable_base,
741                 nested: o.nested.into_iter().map(f).collect(),
742             }),
743             VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
744                 trait_def_id: d.trait_def_id,
745                 nested: d.nested.into_iter().map(f).collect(),
746             }),
747             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
748                 fn_ty: p.fn_ty,
749                 nested: p.nested.into_iter().map(f).collect(),
750             }),
751             VtableClosure(c) => VtableClosure(VtableClosureData {
752                 closure_def_id: c.closure_def_id,
753                 substs: c.substs,
754                 nested: c.nested.into_iter().map(f).collect(),
755             })
756         }
757     }
758 }
759
760 impl<'tcx> FulfillmentError<'tcx> {
761     fn new(obligation: PredicateObligation<'tcx>,
762            code: FulfillmentErrorCode<'tcx>)
763            -> FulfillmentError<'tcx>
764     {
765         FulfillmentError { obligation: obligation, code: code }
766     }
767 }
768
769 impl<'tcx> TraitObligation<'tcx> {
770     fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
771         ty::Binder(self.predicate.skip_binder().self_ty())
772     }
773 }