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