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 infer::outlives::env::OutlivesEnvironment;
21 use middle::const_val::ConstEvalErr;
23 use ty::subst::Substs;
24 use ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, ToPredicate};
25 use ty::error::{ExpectedFound, TypeError};
26 use infer::{InferCtxt};
30 use syntax_pos::{Span, DUMMY_SP};
32 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
33 pub use self::fulfill::FulfillmentContext;
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::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
40 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
41 pub use self::select::IntercrateAmbiguityCause;
42 pub use self::specialize::{OverlapError, specialization_graph, 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;
63 // Whether to enable bug compatibility with issue #43355
64 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
65 pub enum IntercrateMode {
70 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
71 /// which the vtable must be found. The process of finding a vtable is
72 /// called "resolving" the `Obligation`. This process consists of
73 /// either identifying an `impl` (e.g., `impl Eq for int`) that
74 /// provides the required vtable, or else finding a bound that is in
75 /// scope. The eventual result is usually a `Selection` (defined below).
76 #[derive(Clone, PartialEq, Eq)]
77 pub struct Obligation<'tcx, T> {
78 pub cause: ObligationCause<'tcx>,
79 pub param_env: ty::ParamEnv<'tcx>,
80 pub recursion_depth: usize,
84 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
85 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
87 /// Why did we incur this obligation? Used for error reporting.
88 #[derive(Clone, Debug, PartialEq, Eq)]
89 pub struct ObligationCause<'tcx> {
92 // The id of the fn body that triggered this obligation. This is
93 // used for region obligations to determine the precise
94 // environment in which the region obligation should be evaluated
95 // (in particular, closures can add new assumptions). See the
96 // field `region_obligations` of the `FulfillmentContext` for more
98 pub body_id: ast::NodeId,
100 pub code: ObligationCauseCode<'tcx>
103 impl<'tcx> ObligationCause<'tcx> {
104 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
106 ObligationCauseCode::CompareImplMethodObligation { .. } |
107 ObligationCauseCode::MainFunctionType |
108 ObligationCauseCode::StartFunctionType => {
109 tcx.sess.codemap().def_span(self.span)
116 #[derive(Clone, Debug, PartialEq, Eq)]
117 pub enum ObligationCauseCode<'tcx> {
118 /// Not well classified or should be obvious from span.
121 /// A slice or array is WF only if `T: Sized`
124 /// A tuple is WF only if its middle elements are Sized
127 /// This is the trait reference from the given projection
128 ProjectionWf(ty::ProjectionTy<'tcx>),
130 /// In an impl of trait X for type Y, type Y must
131 /// also implement all supertraits of X.
132 ItemObligation(DefId),
134 /// A type like `&'a T` is WF only if `T: 'a`.
135 ReferenceOutlivesReferent(Ty<'tcx>),
137 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
138 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
140 /// Obligation incurred due to an object cast.
141 ObjectCastObligation(/* Object type */ Ty<'tcx>),
143 // Various cases where expressions must be sized/copy/etc:
144 /// L = X implies that L is Sized
146 /// (x1, .., xn) must be Sized
147 TupleInitializerSized,
148 /// S { ... } must be Sized
149 StructInitializerSized,
150 /// Type of each variable must be Sized
151 VariableType(ast::NodeId),
152 /// Return type must be Sized
154 /// Yield type must be Sized
156 /// [T,..n] --> T must be Copy
159 /// Types of fields (other than the last) in a struct must be sized.
162 /// Constant expressions must be sized.
165 /// static items must have `Sync` type
168 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
170 ImplDerivedObligation(DerivedObligationCause<'tcx>),
172 /// error derived when matching traits/impls; see ObligationCause for more details
173 CompareImplMethodObligation {
174 item_name: ast::Name,
175 impl_item_def_id: DefId,
176 trait_item_def_id: DefId,
179 /// Checking that this expression can be assigned where it needs to be
180 // FIXME(eddyb) #11161 is the original Expr required?
183 /// Computing common supertype in the arms of a match expression
184 MatchExpressionArm { arm_span: Span,
185 source: hir::MatchSource },
187 /// Computing common supertype in an if expression
190 /// Computing common supertype of an if expression with no else counter-part
191 IfExpressionWithNoElse,
196 /// `main` has wrong type
199 /// `start` has wrong type
202 /// intrinsic has wrong type
208 /// `return` with no expression
211 /// `return` with an expression
212 ReturnType(ast::NodeId),
214 /// Block implicit return
215 BlockTailExpression(ast::NodeId),
218 #[derive(Clone, Debug, PartialEq, Eq)]
219 pub struct DerivedObligationCause<'tcx> {
220 /// The trait reference of the parent obligation that led to the
221 /// current obligation. Note that only trait obligations lead to
222 /// derived obligations, so we just store the trait reference here
224 parent_trait_ref: ty::PolyTraitRef<'tcx>,
226 /// The parent trait had this cause
227 parent_code: Rc<ObligationCauseCode<'tcx>>
230 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
231 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
232 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
234 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
236 #[derive(Clone,Debug)]
237 pub enum SelectionError<'tcx> {
239 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
240 ty::PolyTraitRef<'tcx>,
241 ty::error::TypeError<'tcx>),
242 TraitNotObjectSafe(DefId),
243 ConstEvalFailure(ConstEvalErr<'tcx>),
246 pub struct FulfillmentError<'tcx> {
247 pub obligation: PredicateObligation<'tcx>,
248 pub code: FulfillmentErrorCode<'tcx>
252 pub enum FulfillmentErrorCode<'tcx> {
253 CodeSelectionError(SelectionError<'tcx>),
254 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
255 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
256 TypeError<'tcx>), // always comes from a SubtypePredicate
260 /// When performing resolution, it is typically the case that there
261 /// can be one of three outcomes:
263 /// - `Ok(Some(r))`: success occurred with result `r`
264 /// - `Ok(None)`: could not definitely determine anything, usually due
265 /// to inconclusive type inference.
266 /// - `Err(e)`: error `e` occurred
267 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
269 /// Given the successful resolution of an obligation, the `Vtable`
270 /// indicates where the vtable comes from. Note that while we call this
271 /// a "vtable", it does not necessarily indicate dynamic dispatch at
272 /// runtime. `Vtable` instances just tell the compiler where to find
273 /// methods, but in generic code those methods are typically statically
274 /// dispatched -- only when an object is constructed is a `Vtable`
275 /// instance reified into an actual vtable.
277 /// For example, the vtable may be tied to a specific impl (case A),
278 /// or it may be relative to some bound that is in scope (case B).
282 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
283 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
284 /// impl Clone for int { ... } // Impl_3
286 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
288 /// mixed: Option<T>) {
290 /// // Case A: Vtable points at a specific impl. Only possible when
291 /// // type is concretely known. If the impl itself has bounded
292 /// // type parameters, Vtable will carry resolutions for those as well:
293 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
295 /// // Case B: Vtable must be provided by caller. This applies when
296 /// // type is a type parameter.
297 /// param.clone(); // VtableParam
299 /// // Case C: A mix of cases A and B.
300 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
304 /// ### The type parameter `N`
306 /// See explanation on `VtableImplData`.
307 #[derive(Clone, RustcEncodable, RustcDecodable)]
308 pub enum Vtable<'tcx, N> {
309 /// Vtable identifying a particular impl.
310 VtableImpl(VtableImplData<'tcx, N>),
312 /// Vtable for auto trait implementations
313 /// This carries the information and nested obligations with regards
314 /// to an auto implementation for a trait `Trait`. The nested obligations
315 /// ensure the trait implementation holds for all the constituent types.
316 VtableAutoImpl(VtableAutoImplData<N>),
318 /// Successful resolution to an obligation provided by the caller
319 /// for some type parameter. The `Vec<N>` represents the
320 /// obligations incurred from normalizing the where-clause (if
324 /// Virtual calls through an object
325 VtableObject(VtableObjectData<'tcx, N>),
327 /// Successful resolution for a builtin trait.
328 VtableBuiltin(VtableBuiltinData<N>),
330 /// Vtable automatically generated for a closure. The def ID is the ID
331 /// of the closure expression. This is a `VtableImpl` in spirit, but the
332 /// impl is generated by the compiler and does not appear in the source.
333 VtableClosure(VtableClosureData<'tcx, N>),
335 /// Same as above, but for a fn pointer type with the given signature.
336 VtableFnPointer(VtableFnPointerData<'tcx, N>),
338 /// Vtable automatically generated for a generator
339 VtableGenerator(VtableGeneratorData<'tcx, N>),
342 /// Identifies a particular impl in the source, along with a set of
343 /// substitutions from the impl's type/lifetime parameters. The
344 /// `nested` vector corresponds to the nested obligations attached to
345 /// the impl's type parameters.
347 /// The type parameter `N` indicates the type used for "nested
348 /// obligations" that are required by the impl. During type check, this
349 /// is `Obligation`, as one might expect. During trans, however, this
350 /// is `()`, because trans only requires a shallow resolution of an
351 /// impl, and nested obligations are satisfied later.
352 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
353 pub struct VtableImplData<'tcx, N> {
354 pub impl_def_id: DefId,
355 pub substs: &'tcx Substs<'tcx>,
359 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
360 pub struct VtableGeneratorData<'tcx, N> {
361 pub closure_def_id: DefId,
362 pub substs: ty::ClosureSubsts<'tcx>,
363 /// Nested obligations. This can be non-empty if the generator
364 /// signature contains associated types.
368 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
369 pub struct VtableClosureData<'tcx, N> {
370 pub closure_def_id: DefId,
371 pub substs: ty::ClosureSubsts<'tcx>,
372 /// Nested obligations. This can be non-empty if the closure
373 /// signature contains associated types.
377 #[derive(Clone, RustcEncodable, RustcDecodable)]
378 pub struct VtableAutoImplData<N> {
379 pub trait_def_id: DefId,
383 #[derive(Clone, RustcEncodable, RustcDecodable)]
384 pub struct VtableBuiltinData<N> {
388 /// A vtable for some object-safe trait `Foo` automatically derived
389 /// for the object type `Foo`.
390 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
391 pub struct VtableObjectData<'tcx, N> {
392 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
393 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
395 /// The vtable is formed by concatenating together the method lists of
396 /// the base object trait and all supertraits; this is the start of
397 /// `upcast_trait_ref`'s methods in that vtable.
398 pub vtable_base: usize,
403 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
404 pub struct VtableFnPointerData<'tcx, N> {
409 /// Creates predicate obligations from the generic bounds.
410 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
411 param_env: ty::ParamEnv<'tcx>,
412 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
413 -> PredicateObligations<'tcx>
415 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
418 /// Determines whether the type `ty` is known to meet `bound` and
419 /// returns true if so. Returns false if `ty` either does not meet
420 /// `bound` or is not known to meet bound (note that this is
421 /// conservative towards *no impl*, which is the opposite of the
422 /// `evaluate` methods).
423 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
424 param_env: ty::ParamEnv<'tcx>,
430 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
432 infcx.tcx.item_path_str(def_id));
434 let trait_ref = ty::TraitRef {
436 substs: infcx.tcx.mk_substs_trait(ty, &[]),
438 let obligation = Obligation {
440 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
442 predicate: trait_ref.to_predicate(),
445 let result = SelectionContext::new(infcx)
446 .evaluate_obligation_conservatively(&obligation);
447 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
448 ty, infcx.tcx.item_path_str(def_id), result);
450 if result && (ty.has_infer_types() || ty.has_closure_types()) {
451 // Because of inference "guessing", selection can sometimes claim
452 // to succeed while the success requires a guess. To ensure
453 // this function's result remains infallible, we must confirm
454 // that guess. While imperfect, I believe this is sound.
456 // The handling of regions in this area of the code is terrible,
457 // see issue #29149. We should be able to improve on this with
459 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
461 // We can use a dummy node-id here because we won't pay any mind
462 // to region obligations that arise (there shouldn't really be any
464 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
466 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
468 // Note: we only assume something is `Copy` if we can
469 // *definitively* show that it implements `Copy`. Otherwise,
470 // assume it is move; linear is always ok.
471 match fulfill_cx.select_all_or_error(infcx) {
473 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
475 infcx.tcx.item_path_str(def_id));
479 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
481 infcx.tcx.item_path_str(def_id),
491 // FIXME: this is gonna need to be removed ...
492 /// Normalizes the parameter environment, reporting errors if they occur.
493 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
494 region_context: DefId,
495 unnormalized_env: ty::ParamEnv<'tcx>,
496 cause: ObligationCause<'tcx>)
497 -> ty::ParamEnv<'tcx>
499 // I'm not wild about reporting errors here; I'd prefer to
500 // have the errors get reported at a defined place (e.g.,
501 // during typeck). Instead I have all parameter
502 // environments, in effect, going through this function
503 // and hence potentially reporting errors. This ensurse of
504 // course that we never forget to normalize (the
505 // alternative seemed like it would involve a lot of
506 // manual invocations of this fn -- and then we'd have to
507 // deal with the errors at each of those sites).
509 // In any case, in practice, typeck constructs all the
510 // parameter environments once for every fn as it goes,
511 // and errors will get reported then; so after typeck we
512 // can be sure that no errors should occur.
514 let span = cause.span;
516 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
519 let predicates: Vec<_> =
520 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
521 .filter(|p| !p.is_global()) // (*)
524 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
525 // need to be in the *environment* to be proven, so screen those
526 // out. This is important for the soundness of inter-fn
527 // caching. Note though that we should probably check that these
528 // predicates hold at the point where the environment is
529 // constructed, but I am not currently doing so out of laziness.
532 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
535 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
536 unnormalized_env.reveal);
538 tcx.infer_ctxt().enter(|infcx| {
539 // FIXME. We should really... do something with these region
540 // obligations. But this call just continues the older
541 // behavior (i.e., doesn't cause any new bugs), and it would
542 // take some further refactoring to actually solve them. In
543 // particular, we would have to handle implied bounds
544 // properly, and that code is currently largely confined to
545 // regionck (though I made some efforts to extract it
548 // @arielby: In any case, these obligations are checked
549 // by wfcheck anyway, so I'm not sure we have to check
550 // them here too, and we will remove this function when
551 // we move over to lazy normalization *anyway*.
552 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
554 let predicates = match fully_normalize_with_fulfillcx(
559 // You would really want to pass infcx.param_env.caller_bounds here,
560 // but that is an interned slice, and fully_normalize takes &T and returns T, so
561 // without further refactoring, a slice can't be used. Luckily, we still have the
562 // predicate vector from which we created the ParamEnv in infcx, so we
563 // can pass that instead. It's roundabout and a bit brittle, but this code path
564 // ought to be refactored anyway, and until then it saves us from having to copy.
567 Ok(predicates) => predicates,
569 infcx.report_fulfillment_errors(&errors, None);
570 // An unnormalized env is better than nothing.
571 return elaborated_env;
575 debug!("normalize_param_env_or_error: normalized predicates={:?}",
578 let region_scope_tree = region::ScopeTree::default();
580 // We can use the `elaborated_env` here; the region code only
581 // cares about declarations like `'a: 'b`.
582 let outlives_env = OutlivesEnvironment::new(elaborated_env);
584 infcx.resolve_regions_and_report_errors(region_context, ®ion_scope_tree, &outlives_env);
586 let predicates = match infcx.fully_resolve(&predicates) {
587 Ok(predicates) => predicates,
589 // If we encounter a fixup error, it means that some type
590 // variable wound up unconstrained. I actually don't know
591 // if this can happen, and I certainly don't expect it to
592 // happen often, but if it did happen it probably
593 // represents a legitimate failure due to some kind of
594 // unconstrained variable, and it seems better not to ICE,
595 // all things considered.
596 tcx.sess.span_err(span, &fixup_err.to_string());
597 // An unnormalized env is better than nothing.
598 return elaborated_env;
602 let predicates = match tcx.lift_to_global(&predicates) {
603 Some(predicates) => predicates,
604 None => return elaborated_env,
607 debug!("normalize_param_env_or_error: resolved predicates={:?}",
610 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
614 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
615 cause: ObligationCause<'tcx>,
616 param_env: ty::ParamEnv<'tcx>,
618 -> Result<T, Vec<FulfillmentError<'tcx>>>
619 where T : TypeFoldable<'tcx>
621 // FIXME (@jroesch) ISSUE 26721
622 // I'm not sure if this is a bug or not, needs further investigation.
623 // It appears that by reusing the fulfillment_cx here we incur more
624 // obligations and later trip an asssertion on regionck.rs line 337.
626 // The two possibilities I see is:
627 // - normalization is not actually fully happening and we
628 // have a bug else where
629 // - we are adding a duplicate bound into the list causing
630 // its size to change.
632 // I think we should probably land this refactor and then come
633 // back to this is a follow-up patch.
634 let fulfillcx = FulfillmentContext::new();
635 fully_normalize_with_fulfillcx(infcx, fulfillcx, cause, param_env, value)
638 pub fn fully_normalize_with_fulfillcx<'a, 'gcx, 'tcx, T>(
639 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
640 mut fulfill_cx: FulfillmentContext<'tcx>,
641 cause: ObligationCause<'tcx>,
642 param_env: ty::ParamEnv<'tcx>,
644 -> Result<T, Vec<FulfillmentError<'tcx>>>
645 where T : TypeFoldable<'tcx>
647 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
648 let selcx = &mut SelectionContext::new(infcx);
649 let Normalized { value: normalized_value, obligations } =
650 project::normalize(selcx, param_env, cause, value);
651 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
654 for obligation in obligations {
655 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
658 debug!("fully_normalize: select_all_or_error start");
659 match fulfill_cx.select_all_or_error(infcx) {
662 debug!("fully_normalize: error={:?}", e);
666 debug!("fully_normalize: select_all_or_error complete");
667 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
668 debug!("fully_normalize: resolved_value={:?}", resolved_value);
672 /// Normalizes the predicates and checks whether they hold in an empty
673 /// environment. If this returns false, then either normalize
674 /// encountered an error or one of the predicates did not hold. Used
675 /// when creating vtables to check for unsatisfiable methods.
676 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
677 predicates: Vec<ty::Predicate<'tcx>>)
680 debug!("normalize_and_test_predicates(predicates={:?})",
683 let result = tcx.infer_ctxt().enter(|infcx| {
684 let param_env = ty::ParamEnv::empty(Reveal::All);
685 let mut selcx = SelectionContext::new(&infcx);
686 let mut fulfill_cx = FulfillmentContext::new();
687 let cause = ObligationCause::dummy();
688 let Normalized { value: predicates, obligations } =
689 normalize(&mut selcx, param_env, cause.clone(), &predicates);
690 for obligation in obligations {
691 fulfill_cx.register_predicate_obligation(&infcx, obligation);
693 for predicate in predicates {
694 let obligation = Obligation::new(cause.clone(), param_env, predicate);
695 fulfill_cx.register_predicate_obligation(&infcx, obligation);
698 fulfill_cx.select_all_or_error(&infcx).is_ok()
700 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
705 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
706 key: (DefId, &'tcx Substs<'tcx>))
709 use ty::subst::Subst;
710 debug!("substitute_normalize_and_test_predicates(key={:?})",
713 let predicates = tcx.predicates_of(key.0).predicates.subst(tcx, key.1);
714 let result = normalize_and_test_predicates(tcx, predicates);
716 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
721 /// Given a trait `trait_ref`, iterates the vtable entries
722 /// that come from `trait_ref`, including its supertraits.
723 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
724 fn vtable_methods<'a, 'tcx>(
725 tcx: TyCtxt<'a, 'tcx, 'tcx>,
726 trait_ref: ty::PolyTraitRef<'tcx>)
727 -> Rc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
729 debug!("vtable_methods({:?})", trait_ref);
732 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
733 let trait_methods = tcx.associated_items(trait_ref.def_id())
734 .filter(|item| item.kind == ty::AssociatedKind::Method);
736 // Now list each method's DefId and Substs (for within its trait).
737 // If the method can never be called from this object, produce None.
738 trait_methods.map(move |trait_method| {
739 debug!("vtable_methods: trait_method={:?}", trait_method);
740 let def_id = trait_method.def_id;
742 // Some methods cannot be called on an object; skip those.
743 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
744 debug!("vtable_methods: not vtable safe");
748 // the method may have some early-bound lifetimes, add
750 let substs = Substs::for_item(tcx, def_id,
751 |_, _| tcx.types.re_erased,
752 |def, _| trait_ref.substs().type_for_def(def));
754 // the trait type may have higher-ranked lifetimes in it;
755 // so erase them if they appear, so that we get the type
756 // at some particular call site
757 let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
759 // It's possible that the method relies on where clauses that
760 // do not hold for this particular set of type parameters.
761 // Note that this method could then never be called, so we
762 // do not want to try and trans it, in that case (see #23435).
763 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
764 if !normalize_and_test_predicates(tcx, predicates.predicates) {
765 debug!("vtable_methods: predicates do not hold");
769 Some((def_id, substs))
775 impl<'tcx,O> Obligation<'tcx,O> {
776 pub fn new(cause: ObligationCause<'tcx>,
777 param_env: ty::ParamEnv<'tcx>,
779 -> Obligation<'tcx, O>
781 Obligation { cause, param_env, recursion_depth: 0, predicate }
784 fn with_depth(cause: ObligationCause<'tcx>,
785 recursion_depth: usize,
786 param_env: ty::ParamEnv<'tcx>,
788 -> Obligation<'tcx, O>
790 Obligation { cause, param_env, recursion_depth, predicate }
793 pub fn misc(span: Span,
794 body_id: ast::NodeId,
795 param_env: ty::ParamEnv<'tcx>,
797 -> Obligation<'tcx, O> {
798 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
801 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
802 Obligation { cause: self.cause.clone(),
803 param_env: self.param_env,
804 recursion_depth: self.recursion_depth,
809 impl<'tcx> ObligationCause<'tcx> {
810 pub fn new(span: Span,
811 body_id: ast::NodeId,
812 code: ObligationCauseCode<'tcx>)
813 -> ObligationCause<'tcx> {
814 ObligationCause { span: span, body_id: body_id, code: code }
817 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
818 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
821 pub fn dummy() -> ObligationCause<'tcx> {
822 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
826 impl<'tcx, N> Vtable<'tcx, N> {
827 pub fn nested_obligations(self) -> Vec<N> {
829 VtableImpl(i) => i.nested,
831 VtableBuiltin(i) => i.nested,
832 VtableAutoImpl(d) => d.nested,
833 VtableClosure(c) => c.nested,
834 VtableGenerator(c) => c.nested,
835 VtableObject(d) => d.nested,
836 VtableFnPointer(d) => d.nested,
840 fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
842 &mut VtableImpl(ref mut i) => &mut i.nested,
843 &mut VtableParam(ref mut n) => n,
844 &mut VtableBuiltin(ref mut i) => &mut i.nested,
845 &mut VtableAutoImpl(ref mut d) => &mut d.nested,
846 &mut VtableGenerator(ref mut c) => &mut c.nested,
847 &mut VtableClosure(ref mut c) => &mut c.nested,
848 &mut VtableObject(ref mut d) => &mut d.nested,
849 &mut VtableFnPointer(ref mut d) => &mut d.nested,
853 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
855 VtableImpl(i) => VtableImpl(VtableImplData {
856 impl_def_id: i.impl_def_id,
858 nested: i.nested.into_iter().map(f).collect(),
860 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
861 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
862 nested: i.nested.into_iter().map(f).collect(),
864 VtableObject(o) => VtableObject(VtableObjectData {
865 upcast_trait_ref: o.upcast_trait_ref,
866 vtable_base: o.vtable_base,
867 nested: o.nested.into_iter().map(f).collect(),
869 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
870 trait_def_id: d.trait_def_id,
871 nested: d.nested.into_iter().map(f).collect(),
873 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
875 nested: p.nested.into_iter().map(f).collect(),
877 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
878 closure_def_id: c.closure_def_id,
880 nested: c.nested.into_iter().map(f).collect(),
882 VtableClosure(c) => VtableClosure(VtableClosureData {
883 closure_def_id: c.closure_def_id,
885 nested: c.nested.into_iter().map(f).collect(),
891 impl<'tcx> FulfillmentError<'tcx> {
892 fn new(obligation: PredicateObligation<'tcx>,
893 code: FulfillmentErrorCode<'tcx>)
894 -> FulfillmentError<'tcx>
896 FulfillmentError { obligation: obligation, code: code }
900 impl<'tcx> TraitObligation<'tcx> {
901 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
902 ty::Binder(self.predicate.skip_binder().self_ty())
906 pub fn provide(providers: &mut ty::maps::Providers) {
907 *providers = ty::maps::Providers {
908 is_object_safe: object_safety::is_object_safe_provider,
909 specialization_graph_of: specialize::specialization_graph_provider,
910 specializes: specialize::specializes,
911 trans_fulfill_obligation: trans::trans_fulfill_obligation,
913 substitute_normalize_and_test_predicates,