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 [rustc guide] for more info on how this works.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/trait-resolution.html
15 pub use self::SelectionError::*;
16 pub use self::FulfillmentErrorCode::*;
17 pub use self::Vtable::*;
18 pub use self::ObligationCauseCode::*;
21 use hir::def_id::DefId;
22 use infer::outlives::env::OutlivesEnvironment;
24 use middle::const_val::ConstEvalErr;
25 use ty::subst::Substs;
26 use ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, ToPredicate};
27 use ty::error::{ExpectedFound, TypeError};
28 use infer::{InferCtxt};
30 use rustc_data_structures::sync::Lrc;
33 use syntax_pos::{Span, DUMMY_SP};
35 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
36 pub use self::fulfill::FulfillmentContext;
37 pub use self::project::MismatchedProjectionTypes;
38 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
39 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
40 pub use self::object_safety::ObjectSafetyViolation;
41 pub use self::object_safety::MethodViolationCode;
42 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
43 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
44 pub use self::select::IntercrateAmbiguityCause;
45 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
46 pub use self::specialize::{SpecializesCache, find_associated_item};
47 pub use self::util::elaborate_predicates;
48 pub use self::util::supertraits;
49 pub use self::util::Supertraits;
50 pub use self::util::supertrait_def_ids;
51 pub use self::util::SupertraitDefIds;
52 pub use self::util::transitive_bounds;
55 pub mod error_reporting;
66 // Whether to enable bug compatibility with issue #43355
67 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
68 pub enum IntercrateMode {
73 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
74 /// which the vtable must be found. The process of finding a vtable is
75 /// called "resolving" the `Obligation`. This process consists of
76 /// either identifying an `impl` (e.g., `impl Eq for int`) that
77 /// provides the required vtable, or else finding a bound that is in
78 /// scope. The eventual result is usually a `Selection` (defined below).
79 #[derive(Clone, PartialEq, Eq, Hash)]
80 pub struct Obligation<'tcx, T> {
81 /// Why do we have to prove this thing?
82 pub cause: ObligationCause<'tcx>,
84 /// In which environment should we prove this thing?
85 pub param_env: ty::ParamEnv<'tcx>,
87 /// What are we trying to prove?
90 /// If we started proving this as a result of trying to prove
91 /// something else, track the total depth to ensure termination.
92 /// If this goes over a certain threshold, we abort compilation --
93 /// in such cases, we can not say whether or not the predicate
94 /// holds for certain. Stupid halting problem. Such a drag.
95 pub recursion_depth: usize,
98 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
99 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
101 /// Why did we incur this obligation? Used for error reporting.
102 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
103 pub struct ObligationCause<'tcx> {
106 // The id of the fn body that triggered this obligation. This is
107 // used for region obligations to determine the precise
108 // environment in which the region obligation should be evaluated
109 // (in particular, closures can add new assumptions). See the
110 // field `region_obligations` of the `FulfillmentContext` for more
112 pub body_id: ast::NodeId,
114 pub code: ObligationCauseCode<'tcx>
117 impl<'tcx> ObligationCause<'tcx> {
118 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
120 ObligationCauseCode::CompareImplMethodObligation { .. } |
121 ObligationCauseCode::MainFunctionType |
122 ObligationCauseCode::StartFunctionType => {
123 tcx.sess.codemap().def_span(self.span)
130 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
131 pub enum ObligationCauseCode<'tcx> {
132 /// Not well classified or should be obvious from span.
135 /// A slice or array is WF only if `T: Sized`
138 /// A tuple is WF only if its middle elements are Sized
141 /// This is the trait reference from the given projection
142 ProjectionWf(ty::ProjectionTy<'tcx>),
144 /// In an impl of trait X for type Y, type Y must
145 /// also implement all supertraits of X.
146 ItemObligation(DefId),
148 /// A type like `&'a T` is WF only if `T: 'a`.
149 ReferenceOutlivesReferent(Ty<'tcx>),
151 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
152 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
154 /// Obligation incurred due to an object cast.
155 ObjectCastObligation(/* Object type */ Ty<'tcx>),
157 // Various cases where expressions must be sized/copy/etc:
158 /// L = X implies that L is Sized
160 /// (x1, .., xn) must be Sized
161 TupleInitializerSized,
162 /// S { ... } must be Sized
163 StructInitializerSized,
164 /// Type of each variable must be Sized
165 VariableType(ast::NodeId),
166 /// Return type must be Sized
168 /// Yield type must be Sized
170 /// [T,..n] --> T must be Copy
173 /// Types of fields (other than the last) in a struct must be sized.
176 /// Constant expressions must be sized.
179 /// static items must have `Sync` type
182 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
184 ImplDerivedObligation(DerivedObligationCause<'tcx>),
186 /// error derived when matching traits/impls; see ObligationCause for more details
187 CompareImplMethodObligation {
188 item_name: ast::Name,
189 impl_item_def_id: DefId,
190 trait_item_def_id: DefId,
193 /// Checking that this expression can be assigned where it needs to be
194 // FIXME(eddyb) #11161 is the original Expr required?
197 /// Computing common supertype in the arms of a match expression
198 MatchExpressionArm { arm_span: Span,
199 source: hir::MatchSource },
201 /// Computing common supertype in an if expression
204 /// Computing common supertype of an if expression with no else counter-part
205 IfExpressionWithNoElse,
207 /// `main` has wrong type
210 /// `start` has wrong type
213 /// intrinsic has wrong type
219 /// `return` with no expression
222 /// `return` with an expression
223 ReturnType(ast::NodeId),
225 /// Block implicit return
226 BlockTailExpression(ast::NodeId),
229 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
230 pub struct DerivedObligationCause<'tcx> {
231 /// The trait reference of the parent obligation that led to the
232 /// current obligation. Note that only trait obligations lead to
233 /// derived obligations, so we just store the trait reference here
235 parent_trait_ref: ty::PolyTraitRef<'tcx>,
237 /// The parent trait had this cause
238 parent_code: Rc<ObligationCauseCode<'tcx>>
241 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
242 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
243 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
245 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
247 #[derive(Clone,Debug)]
248 pub enum SelectionError<'tcx> {
250 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
251 ty::PolyTraitRef<'tcx>,
252 ty::error::TypeError<'tcx>),
253 TraitNotObjectSafe(DefId),
254 ConstEvalFailure(ConstEvalErr<'tcx>),
257 pub struct FulfillmentError<'tcx> {
258 pub obligation: PredicateObligation<'tcx>,
259 pub code: FulfillmentErrorCode<'tcx>
263 pub enum FulfillmentErrorCode<'tcx> {
264 CodeSelectionError(SelectionError<'tcx>),
265 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
266 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
267 TypeError<'tcx>), // always comes from a SubtypePredicate
271 /// When performing resolution, it is typically the case that there
272 /// can be one of three outcomes:
274 /// - `Ok(Some(r))`: success occurred with result `r`
275 /// - `Ok(None)`: could not definitely determine anything, usually due
276 /// to inconclusive type inference.
277 /// - `Err(e)`: error `e` occurred
278 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
280 /// Given the successful resolution of an obligation, the `Vtable`
281 /// indicates where the vtable comes from. Note that while we call this
282 /// a "vtable", it does not necessarily indicate dynamic dispatch at
283 /// runtime. `Vtable` instances just tell the compiler where to find
284 /// methods, but in generic code those methods are typically statically
285 /// dispatched -- only when an object is constructed is a `Vtable`
286 /// instance reified into an actual vtable.
288 /// For example, the vtable may be tied to a specific impl (case A),
289 /// or it may be relative to some bound that is in scope (case B).
293 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
294 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
295 /// impl Clone for int { ... } // Impl_3
297 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
299 /// mixed: Option<T>) {
301 /// // Case A: Vtable points at a specific impl. Only possible when
302 /// // type is concretely known. If the impl itself has bounded
303 /// // type parameters, Vtable will carry resolutions for those as well:
304 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
306 /// // Case B: Vtable must be provided by caller. This applies when
307 /// // type is a type parameter.
308 /// param.clone(); // VtableParam
310 /// // Case C: A mix of cases A and B.
311 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
315 /// ### The type parameter `N`
317 /// See explanation on `VtableImplData`.
318 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
319 pub enum Vtable<'tcx, N> {
320 /// Vtable identifying a particular impl.
321 VtableImpl(VtableImplData<'tcx, N>),
323 /// Vtable for auto trait implementations
324 /// This carries the information and nested obligations with regards
325 /// to an auto implementation for a trait `Trait`. The nested obligations
326 /// ensure the trait implementation holds for all the constituent types.
327 VtableAutoImpl(VtableAutoImplData<N>),
329 /// Successful resolution to an obligation provided by the caller
330 /// for some type parameter. The `Vec<N>` represents the
331 /// obligations incurred from normalizing the where-clause (if
335 /// Virtual calls through an object
336 VtableObject(VtableObjectData<'tcx, N>),
338 /// Successful resolution for a builtin trait.
339 VtableBuiltin(VtableBuiltinData<N>),
341 /// Vtable automatically generated for a closure. The def ID is the ID
342 /// of the closure expression. This is a `VtableImpl` in spirit, but the
343 /// impl is generated by the compiler and does not appear in the source.
344 VtableClosure(VtableClosureData<'tcx, N>),
346 /// Same as above, but for a fn pointer type with the given signature.
347 VtableFnPointer(VtableFnPointerData<'tcx, N>),
349 /// Vtable automatically generated for a generator
350 VtableGenerator(VtableGeneratorData<'tcx, N>),
353 /// Identifies a particular impl in the source, along with a set of
354 /// substitutions from the impl's type/lifetime parameters. The
355 /// `nested` vector corresponds to the nested obligations attached to
356 /// the impl's type parameters.
358 /// The type parameter `N` indicates the type used for "nested
359 /// obligations" that are required by the impl. During type check, this
360 /// is `Obligation`, as one might expect. During trans, however, this
361 /// is `()`, because trans only requires a shallow resolution of an
362 /// impl, and nested obligations are satisfied later.
363 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
364 pub struct VtableImplData<'tcx, N> {
365 pub impl_def_id: DefId,
366 pub substs: &'tcx Substs<'tcx>,
370 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
371 pub struct VtableGeneratorData<'tcx, N> {
372 pub closure_def_id: DefId,
373 pub substs: ty::ClosureSubsts<'tcx>,
374 /// Nested obligations. This can be non-empty if the generator
375 /// signature contains associated types.
379 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
380 pub struct VtableClosureData<'tcx, N> {
381 pub closure_def_id: DefId,
382 pub substs: ty::ClosureSubsts<'tcx>,
383 /// Nested obligations. This can be non-empty if the closure
384 /// signature contains associated types.
388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
389 pub struct VtableAutoImplData<N> {
390 pub trait_def_id: DefId,
394 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
395 pub struct VtableBuiltinData<N> {
399 /// A vtable for some object-safe trait `Foo` automatically derived
400 /// for the object type `Foo`.
401 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
402 pub struct VtableObjectData<'tcx, N> {
403 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
404 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
406 /// The vtable is formed by concatenating together the method lists of
407 /// the base object trait and all supertraits; this is the start of
408 /// `upcast_trait_ref`'s methods in that vtable.
409 pub vtable_base: usize,
414 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
415 pub struct VtableFnPointerData<'tcx, N> {
420 /// Creates predicate obligations from the generic bounds.
421 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
422 param_env: ty::ParamEnv<'tcx>,
423 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
424 -> PredicateObligations<'tcx>
426 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
429 /// Determines whether the type `ty` is known to meet `bound` and
430 /// returns true if so. Returns false if `ty` either does not meet
431 /// `bound` or is not known to meet bound (note that this is
432 /// conservative towards *no impl*, which is the opposite of the
433 /// `evaluate` methods).
434 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
435 param_env: ty::ParamEnv<'tcx>,
441 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
443 infcx.tcx.item_path_str(def_id));
445 let trait_ref = ty::TraitRef {
447 substs: infcx.tcx.mk_substs_trait(ty, &[]),
449 let obligation = Obligation {
451 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
453 predicate: trait_ref.to_predicate(),
456 let result = SelectionContext::new(infcx)
457 .evaluate_obligation_conservatively(&obligation);
458 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
459 ty, infcx.tcx.item_path_str(def_id), result);
461 if result && (ty.has_infer_types() || ty.has_closure_types()) {
462 // Because of inference "guessing", selection can sometimes claim
463 // to succeed while the success requires a guess. To ensure
464 // this function's result remains infallible, we must confirm
465 // that guess. While imperfect, I believe this is sound.
467 // The handling of regions in this area of the code is terrible,
468 // see issue #29149. We should be able to improve on this with
470 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
472 // We can use a dummy node-id here because we won't pay any mind
473 // to region obligations that arise (there shouldn't really be any
475 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
477 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
479 // Note: we only assume something is `Copy` if we can
480 // *definitively* show that it implements `Copy`. Otherwise,
481 // assume it is move; linear is always ok.
482 match fulfill_cx.select_all_or_error(infcx) {
484 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
486 infcx.tcx.item_path_str(def_id));
490 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
492 infcx.tcx.item_path_str(def_id),
502 // FIXME: this is gonna need to be removed ...
503 /// Normalizes the parameter environment, reporting errors if they occur.
504 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
505 region_context: DefId,
506 unnormalized_env: ty::ParamEnv<'tcx>,
507 cause: ObligationCause<'tcx>)
508 -> ty::ParamEnv<'tcx>
510 // I'm not wild about reporting errors here; I'd prefer to
511 // have the errors get reported at a defined place (e.g.,
512 // during typeck). Instead I have all parameter
513 // environments, in effect, going through this function
514 // and hence potentially reporting errors. This ensurse of
515 // course that we never forget to normalize (the
516 // alternative seemed like it would involve a lot of
517 // manual invocations of this fn -- and then we'd have to
518 // deal with the errors at each of those sites).
520 // In any case, in practice, typeck constructs all the
521 // parameter environments once for every fn as it goes,
522 // and errors will get reported then; so after typeck we
523 // can be sure that no errors should occur.
525 let span = cause.span;
527 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
530 let predicates: Vec<_> =
531 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
532 .filter(|p| !p.is_global()) // (*)
535 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
536 // need to be in the *environment* to be proven, so screen those
537 // out. This is important for the soundness of inter-fn
538 // caching. Note though that we should probably check that these
539 // predicates hold at the point where the environment is
540 // constructed, but I am not currently doing so out of laziness.
543 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
546 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
547 unnormalized_env.reveal,
548 unnormalized_env.universe);
550 tcx.infer_ctxt().enter(|infcx| {
551 // FIXME. We should really... do something with these region
552 // obligations. But this call just continues the older
553 // behavior (i.e., doesn't cause any new bugs), and it would
554 // take some further refactoring to actually solve them. In
555 // particular, we would have to handle implied bounds
556 // properly, and that code is currently largely confined to
557 // regionck (though I made some efforts to extract it
560 // @arielby: In any case, these obligations are checked
561 // by wfcheck anyway, so I'm not sure we have to check
562 // them here too, and we will remove this function when
563 // we move over to lazy normalization *anyway*.
564 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
566 let predicates = match fully_normalize_with_fulfillcx(
571 // You would really want to pass infcx.param_env.caller_bounds here,
572 // but that is an interned slice, and fully_normalize takes &T and returns T, so
573 // without further refactoring, a slice can't be used. Luckily, we still have the
574 // predicate vector from which we created the ParamEnv in infcx, so we
575 // can pass that instead. It's roundabout and a bit brittle, but this code path
576 // ought to be refactored anyway, and until then it saves us from having to copy.
579 Ok(predicates) => predicates,
581 infcx.report_fulfillment_errors(&errors, None);
582 // An unnormalized env is better than nothing.
583 return elaborated_env;
587 debug!("normalize_param_env_or_error: normalized predicates={:?}",
590 let region_scope_tree = region::ScopeTree::default();
592 // We can use the `elaborated_env` here; the region code only
593 // cares about declarations like `'a: 'b`.
594 let outlives_env = OutlivesEnvironment::new(elaborated_env);
596 infcx.resolve_regions_and_report_errors(region_context, ®ion_scope_tree, &outlives_env);
598 let predicates = match infcx.fully_resolve(&predicates) {
599 Ok(predicates) => predicates,
601 // If we encounter a fixup error, it means that some type
602 // variable wound up unconstrained. I actually don't know
603 // if this can happen, and I certainly don't expect it to
604 // happen often, but if it did happen it probably
605 // represents a legitimate failure due to some kind of
606 // unconstrained variable, and it seems better not to ICE,
607 // all things considered.
608 tcx.sess.span_err(span, &fixup_err.to_string());
609 // An unnormalized env is better than nothing.
610 return elaborated_env;
614 let predicates = match tcx.lift_to_global(&predicates) {
615 Some(predicates) => predicates,
616 None => return elaborated_env,
619 debug!("normalize_param_env_or_error: resolved predicates={:?}",
622 ty::ParamEnv::new(tcx.intern_predicates(&predicates),
623 unnormalized_env.reveal,
624 unnormalized_env.universe)
628 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
629 cause: ObligationCause<'tcx>,
630 param_env: ty::ParamEnv<'tcx>,
632 -> Result<T, Vec<FulfillmentError<'tcx>>>
633 where T : TypeFoldable<'tcx>
635 // FIXME (@jroesch) ISSUE 26721
636 // I'm not sure if this is a bug or not, needs further investigation.
637 // It appears that by reusing the fulfillment_cx here we incur more
638 // obligations and later trip an assertion on regionck.rs line 337.
640 // The two possibilities I see is:
641 // - normalization is not actually fully happening and we
642 // have a bug else where
643 // - we are adding a duplicate bound into the list causing
644 // its size to change.
646 // I think we should probably land this refactor and then come
647 // back to this is a follow-up patch.
648 let fulfillcx = FulfillmentContext::new();
649 fully_normalize_with_fulfillcx(infcx, fulfillcx, cause, param_env, value)
652 pub fn fully_normalize_with_fulfillcx<'a, 'gcx, 'tcx, T>(
653 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
654 mut fulfill_cx: FulfillmentContext<'tcx>,
655 cause: ObligationCause<'tcx>,
656 param_env: ty::ParamEnv<'tcx>,
658 -> Result<T, Vec<FulfillmentError<'tcx>>>
659 where T : TypeFoldable<'tcx>
661 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
662 let selcx = &mut SelectionContext::new(infcx);
663 let Normalized { value: normalized_value, obligations } =
664 project::normalize(selcx, param_env, cause, value);
665 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
668 for obligation in obligations {
669 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
672 debug!("fully_normalize: select_all_or_error start");
673 match fulfill_cx.select_all_or_error(infcx) {
676 debug!("fully_normalize: error={:?}", e);
680 debug!("fully_normalize: select_all_or_error complete");
681 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
682 debug!("fully_normalize: resolved_value={:?}", resolved_value);
686 /// Normalizes the predicates and checks whether they hold in an empty
687 /// environment. If this returns false, then either normalize
688 /// encountered an error or one of the predicates did not hold. Used
689 /// when creating vtables to check for unsatisfiable methods.
690 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
691 predicates: Vec<ty::Predicate<'tcx>>)
694 debug!("normalize_and_test_predicates(predicates={:?})",
697 let result = tcx.infer_ctxt().enter(|infcx| {
698 let param_env = ty::ParamEnv::empty(Reveal::All);
699 let mut selcx = SelectionContext::new(&infcx);
700 let mut fulfill_cx = FulfillmentContext::new();
701 let cause = ObligationCause::dummy();
702 let Normalized { value: predicates, obligations } =
703 normalize(&mut selcx, param_env, cause.clone(), &predicates);
704 for obligation in obligations {
705 fulfill_cx.register_predicate_obligation(&infcx, obligation);
707 for predicate in predicates {
708 let obligation = Obligation::new(cause.clone(), param_env, predicate);
709 fulfill_cx.register_predicate_obligation(&infcx, obligation);
712 fulfill_cx.select_all_or_error(&infcx).is_ok()
714 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
719 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
720 key: (DefId, &'tcx Substs<'tcx>))
723 use ty::subst::Subst;
724 debug!("substitute_normalize_and_test_predicates(key={:?})",
727 let predicates = tcx.predicates_of(key.0).predicates.subst(tcx, key.1);
728 let result = normalize_and_test_predicates(tcx, predicates);
730 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
735 /// Given a trait `trait_ref`, iterates the vtable entries
736 /// that come from `trait_ref`, including its supertraits.
737 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
738 fn vtable_methods<'a, 'tcx>(
739 tcx: TyCtxt<'a, 'tcx, 'tcx>,
740 trait_ref: ty::PolyTraitRef<'tcx>)
741 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
743 debug!("vtable_methods({:?})", trait_ref);
746 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
747 let trait_methods = tcx.associated_items(trait_ref.def_id())
748 .filter(|item| item.kind == ty::AssociatedKind::Method);
750 // Now list each method's DefId and Substs (for within its trait).
751 // If the method can never be called from this object, produce None.
752 trait_methods.map(move |trait_method| {
753 debug!("vtable_methods: trait_method={:?}", trait_method);
754 let def_id = trait_method.def_id;
756 // Some methods cannot be called on an object; skip those.
757 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
758 debug!("vtable_methods: not vtable safe");
762 // the method may have some early-bound lifetimes, add
764 let substs = Substs::for_item(tcx, def_id,
765 |_, _| tcx.types.re_erased,
766 |def, _| trait_ref.substs().type_for_def(def));
768 // the trait type may have higher-ranked lifetimes in it;
769 // so erase them if they appear, so that we get the type
770 // at some particular call site
771 let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
773 // It's possible that the method relies on where clauses that
774 // do not hold for this particular set of type parameters.
775 // Note that this method could then never be called, so we
776 // do not want to try and trans it, in that case (see #23435).
777 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
778 if !normalize_and_test_predicates(tcx, predicates.predicates) {
779 debug!("vtable_methods: predicates do not hold");
783 Some((def_id, substs))
789 impl<'tcx,O> Obligation<'tcx,O> {
790 pub fn new(cause: ObligationCause<'tcx>,
791 param_env: ty::ParamEnv<'tcx>,
793 -> Obligation<'tcx, O>
795 Obligation { cause, param_env, recursion_depth: 0, predicate }
798 fn with_depth(cause: ObligationCause<'tcx>,
799 recursion_depth: usize,
800 param_env: ty::ParamEnv<'tcx>,
802 -> Obligation<'tcx, O>
804 Obligation { cause, param_env, recursion_depth, predicate }
807 pub fn misc(span: Span,
808 body_id: ast::NodeId,
809 param_env: ty::ParamEnv<'tcx>,
811 -> Obligation<'tcx, O> {
812 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
815 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
816 Obligation { cause: self.cause.clone(),
817 param_env: self.param_env,
818 recursion_depth: self.recursion_depth,
823 impl<'tcx> ObligationCause<'tcx> {
824 pub fn new(span: Span,
825 body_id: ast::NodeId,
826 code: ObligationCauseCode<'tcx>)
827 -> ObligationCause<'tcx> {
828 ObligationCause { span: span, body_id: body_id, code: code }
831 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
832 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
835 pub fn dummy() -> ObligationCause<'tcx> {
836 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
840 impl<'tcx, N> Vtable<'tcx, N> {
841 pub fn nested_obligations(self) -> Vec<N> {
843 VtableImpl(i) => i.nested,
845 VtableBuiltin(i) => i.nested,
846 VtableAutoImpl(d) => d.nested,
847 VtableClosure(c) => c.nested,
848 VtableGenerator(c) => c.nested,
849 VtableObject(d) => d.nested,
850 VtableFnPointer(d) => d.nested,
854 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
856 VtableImpl(i) => VtableImpl(VtableImplData {
857 impl_def_id: i.impl_def_id,
859 nested: i.nested.into_iter().map(f).collect(),
861 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
862 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
863 nested: i.nested.into_iter().map(f).collect(),
865 VtableObject(o) => VtableObject(VtableObjectData {
866 upcast_trait_ref: o.upcast_trait_ref,
867 vtable_base: o.vtable_base,
868 nested: o.nested.into_iter().map(f).collect(),
870 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
871 trait_def_id: d.trait_def_id,
872 nested: d.nested.into_iter().map(f).collect(),
874 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
876 nested: p.nested.into_iter().map(f).collect(),
878 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
879 closure_def_id: c.closure_def_id,
881 nested: c.nested.into_iter().map(f).collect(),
883 VtableClosure(c) => VtableClosure(VtableClosureData {
884 closure_def_id: c.closure_def_id,
886 nested: c.nested.into_iter().map(f).collect(),
892 impl<'tcx> FulfillmentError<'tcx> {
893 fn new(obligation: PredicateObligation<'tcx>,
894 code: FulfillmentErrorCode<'tcx>)
895 -> FulfillmentError<'tcx>
897 FulfillmentError { obligation: obligation, code: code }
901 impl<'tcx> TraitObligation<'tcx> {
902 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
903 ty::Binder(self.predicate.skip_binder().self_ty())
907 pub fn provide(providers: &mut ty::maps::Providers) {
908 *providers = ty::maps::Providers {
909 is_object_safe: object_safety::is_object_safe_provider,
910 specialization_graph_of: specialize::specialization_graph_provider,
911 specializes: specialize::specializes,
912 trans_fulfill_obligation: trans::trans_fulfill_obligation,
914 substitute_normalize_and_test_predicates,