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.
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.
11 //! Trait Resolution. See README.md for an overview of how this works.
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
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};
27 use syntax_pos::{Span, DUMMY_SP};
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_associated_item};
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;
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,
74 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
75 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
77 /// Why did we incur this obligation? Used for error reporting.
78 #[derive(Clone, Debug, PartialEq, Eq)]
79 pub struct ObligationCause<'tcx> {
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
88 pub body_id: ast::NodeId,
90 pub code: ObligationCauseCode<'tcx>
93 #[derive(Clone, Debug, PartialEq, Eq)]
94 pub enum ObligationCauseCode<'tcx> {
95 /// Not well classified or should be obvious from span.
98 /// A slice or array is WF only if `T: Sized`
101 /// A tuple is WF only if its middle elements are Sized
104 /// This is the trait reference from the given projection
105 ProjectionWf(ty::ProjectionTy<'tcx>),
107 /// In an impl of trait X for type Y, type Y must
108 /// also implement all supertraits of X.
109 ItemObligation(DefId),
111 /// A type like `&'a T` is WF only if `T: 'a`.
112 ReferenceOutlivesReferent(Ty<'tcx>),
114 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
115 ObjectTypeBound(Ty<'tcx>, &'tcx ty::Region),
117 /// Obligation incurred due to an object cast.
118 ObjectCastObligation(/* Object type */ Ty<'tcx>),
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
127 // Types of fields (other than the last) in a struct must be sized.
130 // Constant expressions must be sized.
133 // static items must have `Sync` type
136 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
138 ImplDerivedObligation(DerivedObligationCause<'tcx>),
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>,
148 // Checking that this expression can be assigned where it needs to be
149 // FIXME(eddyb) #11161 is the original Expr required?
152 // Computing common supertype in the arms of a match expression
153 MatchExpressionArm { arm_span: Span,
154 source: hir::MatchSource },
156 // Computing common supertype in an if expression
159 // Computing common supertype of an if expression with no else counter-part
160 IfExpressionWithNoElse,
165 // `main` has wrong type
168 // `start` has wrong type
171 // intrinsic has wrong type
177 // `return` with no expression
181 #[derive(Clone, Debug, PartialEq, Eq)]
182 pub struct DerivedObligationCause<'tcx> {
183 /// The trait reference of the parent obligation that led to the
184 /// current obligation. Note that only trait obligations lead to
185 /// derived obligations, so we just store the trait reference here
187 parent_trait_ref: ty::PolyTraitRef<'tcx>,
189 /// The parent trait had this cause
190 parent_code: Rc<ObligationCauseCode<'tcx>>
193 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
194 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
195 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
197 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
199 #[derive(Clone,Debug)]
200 pub enum SelectionError<'tcx> {
202 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
203 ty::PolyTraitRef<'tcx>,
204 ty::error::TypeError<'tcx>),
205 TraitNotObjectSafe(DefId),
208 pub struct FulfillmentError<'tcx> {
209 pub obligation: PredicateObligation<'tcx>,
210 pub code: FulfillmentErrorCode<'tcx>
214 pub enum FulfillmentErrorCode<'tcx> {
215 CodeSelectionError(SelectionError<'tcx>),
216 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
220 /// When performing resolution, it is typically the case that there
221 /// can be one of three outcomes:
223 /// - `Ok(Some(r))`: success occurred with result `r`
224 /// - `Ok(None)`: could not definitely determine anything, usually due
225 /// to inconclusive type inference.
226 /// - `Err(e)`: error `e` occurred
227 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
229 /// Given the successful resolution of an obligation, the `Vtable`
230 /// indicates where the vtable comes from. Note that while we call this
231 /// a "vtable", it does not necessarily indicate dynamic dispatch at
232 /// runtime. `Vtable` instances just tell the compiler where to find
233 /// methods, but in generic code those methods are typically statically
234 /// dispatched -- only when an object is constructed is a `Vtable`
235 /// instance reified into an actual vtable.
237 /// For example, the vtable may be tied to a specific impl (case A),
238 /// or it may be relative to some bound that is in scope (case B).
242 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
243 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
244 /// impl Clone for int { ... } // Impl_3
246 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
248 /// mixed: Option<T>) {
250 /// // Case A: Vtable points at a specific impl. Only possible when
251 /// // type is concretely known. If the impl itself has bounded
252 /// // type parameters, Vtable will carry resolutions for those as well:
253 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
255 /// // Case B: Vtable must be provided by caller. This applies when
256 /// // type is a type parameter.
257 /// param.clone(); // VtableParam
259 /// // Case C: A mix of cases A and B.
260 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
264 /// ### The type parameter `N`
266 /// See explanation on `VtableImplData`.
268 pub enum Vtable<'tcx, N> {
269 /// Vtable identifying a particular impl.
270 VtableImpl(VtableImplData<'tcx, N>),
272 /// Vtable for default trait implementations
273 /// This carries the information and nested obligations with regards
274 /// to a default implementation for a trait `Trait`. The nested obligations
275 /// ensure the trait implementation holds for all the constituent types.
276 VtableDefaultImpl(VtableDefaultImplData<N>),
278 /// Successful resolution to an obligation provided by the caller
279 /// for some type parameter. The `Vec<N>` represents the
280 /// obligations incurred from normalizing the where-clause (if
284 /// Virtual calls through an object
285 VtableObject(VtableObjectData<'tcx, N>),
287 /// Successful resolution for a builtin trait.
288 VtableBuiltin(VtableBuiltinData<N>),
290 /// Vtable automatically generated for a closure. The def ID is the ID
291 /// of the closure expression. This is a `VtableImpl` in spirit, but the
292 /// impl is generated by the compiler and does not appear in the source.
293 VtableClosure(VtableClosureData<'tcx, N>),
295 /// Same as above, but for a fn pointer type with the given signature.
296 VtableFnPointer(VtableFnPointerData<'tcx, N>),
299 /// Identifies a particular impl in the source, along with a set of
300 /// substitutions from the impl's type/lifetime parameters. The
301 /// `nested` vector corresponds to the nested obligations attached to
302 /// the impl's type parameters.
304 /// The type parameter `N` indicates the type used for "nested
305 /// obligations" that are required by the impl. During type check, this
306 /// is `Obligation`, as one might expect. During trans, however, this
307 /// is `()`, because trans only requires a shallow resolution of an
308 /// impl, and nested obligations are satisfied later.
309 #[derive(Clone, PartialEq, Eq)]
310 pub struct VtableImplData<'tcx, N> {
311 pub impl_def_id: DefId,
312 pub substs: &'tcx Substs<'tcx>,
316 #[derive(Clone, PartialEq, Eq)]
317 pub struct VtableClosureData<'tcx, N> {
318 pub closure_def_id: DefId,
319 pub substs: ty::ClosureSubsts<'tcx>,
320 /// Nested obligations. This can be non-empty if the closure
321 /// signature contains associated types.
326 pub struct VtableDefaultImplData<N> {
327 pub trait_def_id: DefId,
332 pub struct VtableBuiltinData<N> {
336 /// A vtable for some object-safe trait `Foo` automatically derived
337 /// for the object type `Foo`.
338 #[derive(PartialEq,Eq,Clone)]
339 pub struct VtableObjectData<'tcx, N> {
340 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
341 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
343 /// The vtable is formed by concatenating together the method lists of
344 /// the base object trait and all supertraits; this is the start of
345 /// `upcast_trait_ref`'s methods in that vtable.
346 pub vtable_base: usize,
351 #[derive(Clone, PartialEq, Eq)]
352 pub struct VtableFnPointerData<'tcx, N> {
353 pub fn_ty: ty::Ty<'tcx>,
357 /// Creates predicate obligations from the generic bounds.
358 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
359 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
360 -> PredicateObligations<'tcx>
362 util::predicates_for_generics(cause, 0, generic_bounds)
365 /// Determines whether the type `ty` is known to meet `bound` and
366 /// returns true if so. Returns false if `ty` either does not meet
367 /// `bound` or is not known to meet bound (note that this is
368 /// conservative towards *no impl*, which is the opposite of the
369 /// `evaluate` methods).
370 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
376 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
378 infcx.tcx.item_path_str(def_id));
380 let trait_ref = ty::TraitRef {
382 substs: infcx.tcx.mk_substs_trait(ty, &[]),
384 let obligation = Obligation {
385 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
387 predicate: trait_ref.to_predicate(),
390 let result = SelectionContext::new(infcx)
391 .evaluate_obligation_conservatively(&obligation);
392 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
393 ty, infcx.tcx.item_path_str(def_id), result);
395 if result && (ty.has_infer_types() || ty.has_closure_types()) {
396 // Because of inference "guessing", selection can sometimes claim
397 // to succeed while the success requires a guess. To ensure
398 // this function's result remains infallible, we must confirm
399 // that guess. While imperfect, I believe this is sound.
401 let mut fulfill_cx = FulfillmentContext::new();
403 // We can use a dummy node-id here because we won't pay any mind
404 // to region obligations that arise (there shouldn't really be any
406 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
408 fulfill_cx.register_bound(infcx, ty, def_id, cause);
410 // Note: we only assume something is `Copy` if we can
411 // *definitively* show that it implements `Copy`. Otherwise,
412 // assume it is move; linear is always ok.
413 match fulfill_cx.select_all_or_error(infcx) {
415 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
417 infcx.tcx.item_path_str(def_id));
421 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
423 infcx.tcx.item_path_str(def_id),
433 // FIXME: this is gonna need to be removed ...
434 /// Normalizes the parameter environment, reporting errors if they occur.
435 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
436 unnormalized_env: ty::ParameterEnvironment<'tcx>,
437 cause: ObligationCause<'tcx>)
438 -> ty::ParameterEnvironment<'tcx>
440 // I'm not wild about reporting errors here; I'd prefer to
441 // have the errors get reported at a defined place (e.g.,
442 // during typeck). Instead I have all parameter
443 // environments, in effect, going through this function
444 // and hence potentially reporting errors. This ensurse of
445 // course that we never forget to normalize (the
446 // alternative seemed like it would involve a lot of
447 // manual invocations of this fn -- and then we'd have to
448 // deal with the errors at each of those sites).
450 // In any case, in practice, typeck constructs all the
451 // parameter environments once for every fn as it goes,
452 // and errors will get reported then; so after typeck we
453 // can be sure that no errors should occur.
455 let span = cause.span;
456 let body_id = cause.body_id;
458 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
461 let predicates: Vec<_> =
462 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
463 .filter(|p| !p.is_global()) // (*)
466 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
467 // need to be in the *environment* to be proven, so screen those
468 // out. This is important for the soundness of inter-fn
469 // caching. Note though that we should probably check that these
470 // predicates hold at the point where the environment is
471 // constructed, but I am not currently doing so out of laziness.
474 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
477 let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
479 tcx.infer_ctxt(elaborated_env, Reveal::UserFacing).enter(|infcx| {
480 let predicates = match fully_normalize(&infcx, cause,
481 &infcx.parameter_environment.caller_bounds) {
482 Ok(predicates) => predicates,
484 infcx.report_fulfillment_errors(&errors);
485 // An unnormalized env is better than nothing.
486 return infcx.parameter_environment;
490 debug!("normalize_param_env_or_error: normalized predicates={:?}",
493 let free_regions = FreeRegionMap::new();
494 infcx.resolve_regions_and_report_errors(&free_regions, body_id);
495 let predicates = match infcx.fully_resolve(&predicates) {
496 Ok(predicates) => predicates,
498 // If we encounter a fixup error, it means that some type
499 // variable wound up unconstrained. I actually don't know
500 // if this can happen, and I certainly don't expect it to
501 // happen often, but if it did happen it probably
502 // represents a legitimate failure due to some kind of
503 // unconstrained variable, and it seems better not to ICE,
504 // all things considered.
505 tcx.sess.span_err(span, &fixup_err.to_string());
506 // An unnormalized env is better than nothing.
507 return infcx.parameter_environment;
511 let predicates = match tcx.lift_to_global(&predicates) {
512 Some(predicates) => predicates,
513 None => return infcx.parameter_environment
516 debug!("normalize_param_env_or_error: resolved predicates={:?}",
519 infcx.parameter_environment.with_caller_bounds(predicates)
523 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
524 cause: ObligationCause<'tcx>,
526 -> Result<T, Vec<FulfillmentError<'tcx>>>
527 where T : TypeFoldable<'tcx>
529 debug!("fully_normalize(value={:?})", value);
531 let mut selcx = &mut SelectionContext::new(infcx);
532 // FIXME (@jroesch) ISSUE 26721
533 // I'm not sure if this is a bug or not, needs further investigation.
534 // It appears that by reusing the fulfillment_cx here we incur more
535 // obligations and later trip an asssertion on regionck.rs line 337.
537 // The two possibilities I see is:
538 // - normalization is not actually fully happening and we
539 // have a bug else where
540 // - we are adding a duplicate bound into the list causing
541 // its size to change.
543 // I think we should probably land this refactor and then come
544 // back to this is a follow-up patch.
545 let mut fulfill_cx = FulfillmentContext::new();
547 let Normalized { value: normalized_value, obligations } =
548 project::normalize(selcx, cause, value);
549 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
552 for obligation in obligations {
553 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
556 debug!("fully_normalize: select_all_or_error start");
557 match fulfill_cx.select_all_or_error(infcx) {
560 debug!("fully_normalize: error={:?}", e);
564 debug!("fully_normalize: select_all_or_error complete");
565 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
566 debug!("fully_normalize: resolved_value={:?}", resolved_value);
570 /// Normalizes the predicates and checks whether they hold. If this
571 /// returns false, then either normalize encountered an error or one
572 /// of the predicates did not hold. Used when creating vtables to
573 /// check for unsatisfiable methods.
574 pub fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
575 predicates: Vec<ty::Predicate<'tcx>>)
578 debug!("normalize_and_test_predicates(predicates={:?})",
581 tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
582 let mut selcx = SelectionContext::new(&infcx);
583 let mut fulfill_cx = FulfillmentContext::new();
584 let cause = ObligationCause::dummy();
585 let Normalized { value: predicates, obligations } =
586 normalize(&mut selcx, cause.clone(), &predicates);
587 for obligation in obligations {
588 fulfill_cx.register_predicate_obligation(&infcx, obligation);
590 for predicate in predicates {
591 let obligation = Obligation::new(cause.clone(), predicate);
592 fulfill_cx.register_predicate_obligation(&infcx, obligation);
595 fulfill_cx.select_all_or_error(&infcx).is_ok()
599 /// Given a trait `trait_ref`, iterates the vtable entries
600 /// that come from `trait_ref`, including its supertraits.
601 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
602 pub fn get_vtable_methods<'a, 'tcx>(
603 tcx: TyCtxt<'a, 'tcx, 'tcx>,
604 trait_ref: ty::PolyTraitRef<'tcx>)
605 -> impl Iterator<Item=Option<(DefId, &'tcx Substs<'tcx>)>> + 'a
607 debug!("get_vtable_methods({:?})", trait_ref);
609 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
610 tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id());
612 let trait_methods = tcx.associated_items(trait_ref.def_id())
613 .filter(|item| item.kind == ty::AssociatedKind::Method);
615 // Now list each method's DefId and Substs (for within its trait).
616 // If the method can never be called from this object, produce None.
617 trait_methods.map(move |trait_method| {
618 debug!("get_vtable_methods: trait_method={:?}", trait_method);
619 let def_id = trait_method.def_id;
621 // Some methods cannot be called on an object; skip those.
622 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
623 debug!("get_vtable_methods: not vtable safe");
627 // the method may have some early-bound lifetimes, add
629 let substs = Substs::for_item(tcx, def_id,
630 |_, _| tcx.mk_region(ty::ReErased),
631 |def, _| trait_ref.substs().type_for_def(def));
633 // the trait type may have higher-ranked lifetimes in it;
634 // so erase them if they appear, so that we get the type
635 // at some particular call site
636 let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
638 // It's possible that the method relies on where clauses that
639 // do not hold for this particular set of type parameters.
640 // Note that this method could then never be called, so we
641 // do not want to try and trans it, in that case (see #23435).
642 let predicates = tcx.item_predicates(def_id).instantiate_own(tcx, substs);
643 if !normalize_and_test_predicates(tcx, predicates.predicates) {
644 debug!("get_vtable_methods: predicates do not hold");
648 Some((def_id, substs))
653 impl<'tcx,O> Obligation<'tcx,O> {
654 pub fn new(cause: ObligationCause<'tcx>,
656 -> Obligation<'tcx, O>
658 Obligation { cause: cause,
660 predicate: trait_ref }
663 fn with_depth(cause: ObligationCause<'tcx>,
664 recursion_depth: usize,
666 -> Obligation<'tcx, O>
668 Obligation { cause: cause,
669 recursion_depth: recursion_depth,
670 predicate: trait_ref }
673 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
674 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
677 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
678 Obligation { cause: self.cause.clone(),
679 recursion_depth: self.recursion_depth,
684 impl<'tcx> ObligationCause<'tcx> {
685 pub fn new(span: Span,
686 body_id: ast::NodeId,
687 code: ObligationCauseCode<'tcx>)
688 -> ObligationCause<'tcx> {
689 ObligationCause { span: span, body_id: body_id, code: code }
692 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
693 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
696 pub fn dummy() -> ObligationCause<'tcx> {
697 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
701 impl<'tcx, N> Vtable<'tcx, N> {
702 pub fn nested_obligations(self) -> Vec<N> {
704 VtableImpl(i) => i.nested,
706 VtableBuiltin(i) => i.nested,
707 VtableDefaultImpl(d) => d.nested,
708 VtableClosure(c) => c.nested,
709 VtableObject(d) => d.nested,
710 VtableFnPointer(d) => d.nested,
714 fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
716 &mut VtableImpl(ref mut i) => &mut i.nested,
717 &mut VtableParam(ref mut n) => n,
718 &mut VtableBuiltin(ref mut i) => &mut i.nested,
719 &mut VtableDefaultImpl(ref mut d) => &mut d.nested,
720 &mut VtableClosure(ref mut c) => &mut c.nested,
721 &mut VtableObject(ref mut d) => &mut d.nested,
722 &mut VtableFnPointer(ref mut d) => &mut d.nested,
726 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
728 VtableImpl(i) => VtableImpl(VtableImplData {
729 impl_def_id: i.impl_def_id,
731 nested: i.nested.into_iter().map(f).collect(),
733 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
734 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
735 nested: i.nested.into_iter().map(f).collect(),
737 VtableObject(o) => VtableObject(VtableObjectData {
738 upcast_trait_ref: o.upcast_trait_ref,
739 vtable_base: o.vtable_base,
740 nested: o.nested.into_iter().map(f).collect(),
742 VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
743 trait_def_id: d.trait_def_id,
744 nested: d.nested.into_iter().map(f).collect(),
746 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
748 nested: p.nested.into_iter().map(f).collect(),
750 VtableClosure(c) => VtableClosure(VtableClosureData {
751 closure_def_id: c.closure_def_id,
753 nested: c.nested.into_iter().map(f).collect(),
759 impl<'tcx> FulfillmentError<'tcx> {
760 fn new(obligation: PredicateObligation<'tcx>,
761 code: FulfillmentErrorCode<'tcx>)
762 -> FulfillmentError<'tcx>
764 FulfillmentError { obligation: obligation, code: code }
768 impl<'tcx> TraitObligation<'tcx> {
769 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
770 ty::Binder(self.predicate.skip_binder().self_ty())