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 #[derive(Clone, Debug, PartialEq, Eq)]
104 pub enum ObligationCauseCode<'tcx> {
105 /// Not well classified or should be obvious from span.
108 /// A slice or array is WF only if `T: Sized`
111 /// A tuple is WF only if its middle elements are Sized
114 /// This is the trait reference from the given projection
115 ProjectionWf(ty::ProjectionTy<'tcx>),
117 /// In an impl of trait X for type Y, type Y must
118 /// also implement all supertraits of X.
119 ItemObligation(DefId),
121 /// A type like `&'a T` is WF only if `T: 'a`.
122 ReferenceOutlivesReferent(Ty<'tcx>),
124 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
125 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
127 /// Obligation incurred due to an object cast.
128 ObjectCastObligation(/* Object type */ Ty<'tcx>),
130 // Various cases where expressions must be sized/copy/etc:
131 /// L = X implies that L is Sized
133 /// (x1, .., xn) must be Sized
134 TupleInitializerSized,
135 /// S { ... } must be Sized
136 StructInitializerSized,
137 /// Type of each variable must be Sized
138 VariableType(ast::NodeId),
139 /// Return type must be Sized
141 /// [T,..n] --> T must be Copy
144 /// Types of fields (other than the last) in a struct must be sized.
147 /// Constant expressions must be sized.
150 /// static items must have `Sync` type
153 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
155 ImplDerivedObligation(DerivedObligationCause<'tcx>),
157 /// error derived when matching traits/impls; see ObligationCause for more details
158 CompareImplMethodObligation {
159 item_name: ast::Name,
160 impl_item_def_id: DefId,
161 trait_item_def_id: DefId,
164 /// Checking that this expression can be assigned where it needs to be
165 // FIXME(eddyb) #11161 is the original Expr required?
168 /// Computing common supertype in the arms of a match expression
169 MatchExpressionArm { arm_span: Span,
170 source: hir::MatchSource },
172 /// Computing common supertype in an if expression
175 /// Computing common supertype of an if expression with no else counter-part
176 IfExpressionWithNoElse,
181 /// `main` has wrong type
184 /// `start` has wrong type
187 /// intrinsic has wrong type
193 /// `return` with no expression
196 /// `return` with an expression
197 ReturnType(ast::NodeId),
199 /// Block implicit return
200 BlockTailExpression(ast::NodeId),
203 #[derive(Clone, Debug, PartialEq, Eq)]
204 pub struct DerivedObligationCause<'tcx> {
205 /// The trait reference of the parent obligation that led to the
206 /// current obligation. Note that only trait obligations lead to
207 /// derived obligations, so we just store the trait reference here
209 parent_trait_ref: ty::PolyTraitRef<'tcx>,
211 /// The parent trait had this cause
212 parent_code: Rc<ObligationCauseCode<'tcx>>
215 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
216 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
217 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
219 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
221 #[derive(Clone,Debug)]
222 pub enum SelectionError<'tcx> {
224 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
225 ty::PolyTraitRef<'tcx>,
226 ty::error::TypeError<'tcx>),
227 TraitNotObjectSafe(DefId),
228 ConstEvalFailure(ConstEvalErr<'tcx>),
231 pub struct FulfillmentError<'tcx> {
232 pub obligation: PredicateObligation<'tcx>,
233 pub code: FulfillmentErrorCode<'tcx>
237 pub enum FulfillmentErrorCode<'tcx> {
238 CodeSelectionError(SelectionError<'tcx>),
239 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
240 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
241 TypeError<'tcx>), // always comes from a SubtypePredicate
245 /// When performing resolution, it is typically the case that there
246 /// can be one of three outcomes:
248 /// - `Ok(Some(r))`: success occurred with result `r`
249 /// - `Ok(None)`: could not definitely determine anything, usually due
250 /// to inconclusive type inference.
251 /// - `Err(e)`: error `e` occurred
252 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
254 /// Given the successful resolution of an obligation, the `Vtable`
255 /// indicates where the vtable comes from. Note that while we call this
256 /// a "vtable", it does not necessarily indicate dynamic dispatch at
257 /// runtime. `Vtable` instances just tell the compiler where to find
258 /// methods, but in generic code those methods are typically statically
259 /// dispatched -- only when an object is constructed is a `Vtable`
260 /// instance reified into an actual vtable.
262 /// For example, the vtable may be tied to a specific impl (case A),
263 /// or it may be relative to some bound that is in scope (case B).
267 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
268 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
269 /// impl Clone for int { ... } // Impl_3
271 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
273 /// mixed: Option<T>) {
275 /// // Case A: Vtable points at a specific impl. Only possible when
276 /// // type is concretely known. If the impl itself has bounded
277 /// // type parameters, Vtable will carry resolutions for those as well:
278 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
280 /// // Case B: Vtable must be provided by caller. This applies when
281 /// // type is a type parameter.
282 /// param.clone(); // VtableParam
284 /// // Case C: A mix of cases A and B.
285 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
289 /// ### The type parameter `N`
291 /// See explanation on `VtableImplData`.
292 #[derive(Clone, RustcEncodable, RustcDecodable)]
293 pub enum Vtable<'tcx, N> {
294 /// Vtable identifying a particular impl.
295 VtableImpl(VtableImplData<'tcx, N>),
297 /// Vtable for auto trait implementations
298 /// This carries the information and nested obligations with regards
299 /// to an auto implementation for a trait `Trait`. The nested obligations
300 /// ensure the trait implementation holds for all the constituent types.
301 VtableAutoImpl(VtableAutoImplData<N>),
303 /// Successful resolution to an obligation provided by the caller
304 /// for some type parameter. The `Vec<N>` represents the
305 /// obligations incurred from normalizing the where-clause (if
309 /// Virtual calls through an object
310 VtableObject(VtableObjectData<'tcx, N>),
312 /// Successful resolution for a builtin trait.
313 VtableBuiltin(VtableBuiltinData<N>),
315 /// Vtable automatically generated for a closure. The def ID is the ID
316 /// of the closure expression. This is a `VtableImpl` in spirit, but the
317 /// impl is generated by the compiler and does not appear in the source.
318 VtableClosure(VtableClosureData<'tcx, N>),
320 /// Same as above, but for a fn pointer type with the given signature.
321 VtableFnPointer(VtableFnPointerData<'tcx, N>),
323 /// Vtable automatically generated for a generator
324 VtableGenerator(VtableGeneratorData<'tcx, N>),
327 /// Identifies a particular impl in the source, along with a set of
328 /// substitutions from the impl's type/lifetime parameters. The
329 /// `nested` vector corresponds to the nested obligations attached to
330 /// the impl's type parameters.
332 /// The type parameter `N` indicates the type used for "nested
333 /// obligations" that are required by the impl. During type check, this
334 /// is `Obligation`, as one might expect. During trans, however, this
335 /// is `()`, because trans only requires a shallow resolution of an
336 /// impl, and nested obligations are satisfied later.
337 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
338 pub struct VtableImplData<'tcx, N> {
339 pub impl_def_id: DefId,
340 pub substs: &'tcx Substs<'tcx>,
344 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
345 pub struct VtableGeneratorData<'tcx, N> {
346 pub closure_def_id: DefId,
347 pub substs: ty::ClosureSubsts<'tcx>,
348 /// Nested obligations. This can be non-empty if the generator
349 /// signature contains associated types.
353 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
354 pub struct VtableClosureData<'tcx, N> {
355 pub closure_def_id: DefId,
356 pub substs: ty::ClosureSubsts<'tcx>,
357 /// Nested obligations. This can be non-empty if the closure
358 /// signature contains associated types.
362 #[derive(Clone, RustcEncodable, RustcDecodable)]
363 pub struct VtableAutoImplData<N> {
364 pub trait_def_id: DefId,
368 #[derive(Clone, RustcEncodable, RustcDecodable)]
369 pub struct VtableBuiltinData<N> {
373 /// A vtable for some object-safe trait `Foo` automatically derived
374 /// for the object type `Foo`.
375 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
376 pub struct VtableObjectData<'tcx, N> {
377 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
378 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
380 /// The vtable is formed by concatenating together the method lists of
381 /// the base object trait and all supertraits; this is the start of
382 /// `upcast_trait_ref`'s methods in that vtable.
383 pub vtable_base: usize,
388 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
389 pub struct VtableFnPointerData<'tcx, N> {
394 /// Creates predicate obligations from the generic bounds.
395 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
396 param_env: ty::ParamEnv<'tcx>,
397 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
398 -> PredicateObligations<'tcx>
400 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
403 /// Determines whether the type `ty` is known to meet `bound` and
404 /// returns true if so. Returns false if `ty` either does not meet
405 /// `bound` or is not known to meet bound (note that this is
406 /// conservative towards *no impl*, which is the opposite of the
407 /// `evaluate` methods).
408 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
409 param_env: ty::ParamEnv<'tcx>,
415 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
417 infcx.tcx.item_path_str(def_id));
419 let trait_ref = ty::TraitRef {
421 substs: infcx.tcx.mk_substs_trait(ty, &[]),
423 let obligation = Obligation {
425 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
427 predicate: trait_ref.to_predicate(),
430 let result = SelectionContext::new(infcx)
431 .evaluate_obligation_conservatively(&obligation);
432 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
433 ty, infcx.tcx.item_path_str(def_id), result);
435 if result && (ty.has_infer_types() || ty.has_closure_types()) {
436 // Because of inference "guessing", selection can sometimes claim
437 // to succeed while the success requires a guess. To ensure
438 // this function's result remains infallible, we must confirm
439 // that guess. While imperfect, I believe this is sound.
441 // The handling of regions in this area of the code is terrible,
442 // see issue #29149. We should be able to improve on this with
444 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
446 // We can use a dummy node-id here because we won't pay any mind
447 // to region obligations that arise (there shouldn't really be any
449 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
451 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
453 // Note: we only assume something is `Copy` if we can
454 // *definitively* show that it implements `Copy`. Otherwise,
455 // assume it is move; linear is always ok.
456 match fulfill_cx.select_all_or_error(infcx) {
458 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
460 infcx.tcx.item_path_str(def_id));
464 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
466 infcx.tcx.item_path_str(def_id),
476 // FIXME: this is gonna need to be removed ...
477 /// Normalizes the parameter environment, reporting errors if they occur.
478 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
479 region_context: DefId,
480 unnormalized_env: ty::ParamEnv<'tcx>,
481 cause: ObligationCause<'tcx>)
482 -> ty::ParamEnv<'tcx>
484 // I'm not wild about reporting errors here; I'd prefer to
485 // have the errors get reported at a defined place (e.g.,
486 // during typeck). Instead I have all parameter
487 // environments, in effect, going through this function
488 // and hence potentially reporting errors. This ensurse of
489 // course that we never forget to normalize (the
490 // alternative seemed like it would involve a lot of
491 // manual invocations of this fn -- and then we'd have to
492 // deal with the errors at each of those sites).
494 // In any case, in practice, typeck constructs all the
495 // parameter environments once for every fn as it goes,
496 // and errors will get reported then; so after typeck we
497 // can be sure that no errors should occur.
499 let span = cause.span;
501 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
504 let predicates: Vec<_> =
505 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
506 .filter(|p| !p.is_global()) // (*)
509 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
510 // need to be in the *environment* to be proven, so screen those
511 // out. This is important for the soundness of inter-fn
512 // caching. Note though that we should probably check that these
513 // predicates hold at the point where the environment is
514 // constructed, but I am not currently doing so out of laziness.
517 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
520 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
521 unnormalized_env.reveal);
523 tcx.infer_ctxt().enter(|infcx| {
524 // FIXME. We should really... do something with these region
525 // obligations. But this call just continues the older
526 // behavior (i.e., doesn't cause any new bugs), and it would
527 // take some further refactoring to actually solve them. In
528 // particular, we would have to handle implied bounds
529 // properly, and that code is currently largely confined to
530 // regionck (though I made some efforts to extract it
533 // @arielby: In any case, these obligations are checked
534 // by wfcheck anyway, so I'm not sure we have to check
535 // them here too, and we will remove this function when
536 // we move over to lazy normalization *anyway*.
537 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
539 let predicates = match fully_normalize_with_fulfillcx(
544 // You would really want to pass infcx.param_env.caller_bounds here,
545 // but that is an interned slice, and fully_normalize takes &T and returns T, so
546 // without further refactoring, a slice can't be used. Luckily, we still have the
547 // predicate vector from which we created the ParamEnv in infcx, so we
548 // can pass that instead. It's roundabout and a bit brittle, but this code path
549 // ought to be refactored anyway, and until then it saves us from having to copy.
552 Ok(predicates) => predicates,
554 infcx.report_fulfillment_errors(&errors, None);
555 // An unnormalized env is better than nothing.
556 return elaborated_env;
560 debug!("normalize_param_env_or_error: normalized predicates={:?}",
563 let region_scope_tree = region::ScopeTree::default();
565 // We can use the `elaborated_env` here; the region code only
566 // cares about declarations like `'a: 'b`.
567 let outlives_env = OutlivesEnvironment::new(elaborated_env);
569 infcx.resolve_regions_and_report_errors(region_context, ®ion_scope_tree, &outlives_env);
571 let predicates = match infcx.fully_resolve(&predicates) {
572 Ok(predicates) => predicates,
574 // If we encounter a fixup error, it means that some type
575 // variable wound up unconstrained. I actually don't know
576 // if this can happen, and I certainly don't expect it to
577 // happen often, but if it did happen it probably
578 // represents a legitimate failure due to some kind of
579 // unconstrained variable, and it seems better not to ICE,
580 // all things considered.
581 tcx.sess.span_err(span, &fixup_err.to_string());
582 // An unnormalized env is better than nothing.
583 return elaborated_env;
587 let predicates = match tcx.lift_to_global(&predicates) {
588 Some(predicates) => predicates,
589 None => return elaborated_env,
592 debug!("normalize_param_env_or_error: resolved predicates={:?}",
595 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
599 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
600 cause: ObligationCause<'tcx>,
601 param_env: ty::ParamEnv<'tcx>,
603 -> Result<T, Vec<FulfillmentError<'tcx>>>
604 where T : TypeFoldable<'tcx>
606 // FIXME (@jroesch) ISSUE 26721
607 // I'm not sure if this is a bug or not, needs further investigation.
608 // It appears that by reusing the fulfillment_cx here we incur more
609 // obligations and later trip an asssertion on regionck.rs line 337.
611 // The two possibilities I see is:
612 // - normalization is not actually fully happening and we
613 // have a bug else where
614 // - we are adding a duplicate bound into the list causing
615 // its size to change.
617 // I think we should probably land this refactor and then come
618 // back to this is a follow-up patch.
619 let fulfillcx = FulfillmentContext::new();
620 fully_normalize_with_fulfillcx(infcx, fulfillcx, cause, param_env, value)
623 pub fn fully_normalize_with_fulfillcx<'a, 'gcx, 'tcx, T>(
624 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
625 mut fulfill_cx: FulfillmentContext<'tcx>,
626 cause: ObligationCause<'tcx>,
627 param_env: ty::ParamEnv<'tcx>,
629 -> Result<T, Vec<FulfillmentError<'tcx>>>
630 where T : TypeFoldable<'tcx>
632 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
633 let selcx = &mut SelectionContext::new(infcx);
634 let Normalized { value: normalized_value, obligations } =
635 project::normalize(selcx, param_env, cause, value);
636 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
639 for obligation in obligations {
640 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
643 debug!("fully_normalize: select_all_or_error start");
644 match fulfill_cx.select_all_or_error(infcx) {
647 debug!("fully_normalize: error={:?}", e);
651 debug!("fully_normalize: select_all_or_error complete");
652 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
653 debug!("fully_normalize: resolved_value={:?}", resolved_value);
657 /// Normalizes the predicates and checks whether they hold in an empty
658 /// environment. If this returns false, then either normalize
659 /// encountered an error or one of the predicates did not hold. Used
660 /// when creating vtables to check for unsatisfiable methods.
661 pub fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
662 predicates: Vec<ty::Predicate<'tcx>>)
665 debug!("normalize_and_test_predicates(predicates={:?})",
668 let result = tcx.infer_ctxt().enter(|infcx| {
669 let param_env = ty::ParamEnv::empty(Reveal::All);
670 let mut selcx = SelectionContext::new(&infcx);
671 let mut fulfill_cx = FulfillmentContext::new();
672 let cause = ObligationCause::dummy();
673 let Normalized { value: predicates, obligations } =
674 normalize(&mut selcx, param_env, cause.clone(), &predicates);
675 for obligation in obligations {
676 fulfill_cx.register_predicate_obligation(&infcx, obligation);
678 for predicate in predicates {
679 let obligation = Obligation::new(cause.clone(), param_env, predicate);
680 fulfill_cx.register_predicate_obligation(&infcx, obligation);
683 fulfill_cx.select_all_or_error(&infcx).is_ok()
685 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
690 /// Given a trait `trait_ref`, iterates the vtable entries
691 /// that come from `trait_ref`, including its supertraits.
692 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
693 fn vtable_methods<'a, 'tcx>(
694 tcx: TyCtxt<'a, 'tcx, 'tcx>,
695 trait_ref: ty::PolyTraitRef<'tcx>)
696 -> Rc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
698 debug!("vtable_methods({:?})", trait_ref);
701 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
702 let trait_methods = tcx.associated_items(trait_ref.def_id())
703 .filter(|item| item.kind == ty::AssociatedKind::Method);
705 // Now list each method's DefId and Substs (for within its trait).
706 // If the method can never be called from this object, produce None.
707 trait_methods.map(move |trait_method| {
708 debug!("vtable_methods: trait_method={:?}", trait_method);
709 let def_id = trait_method.def_id;
711 // Some methods cannot be called on an object; skip those.
712 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
713 debug!("vtable_methods: not vtable safe");
717 // the method may have some early-bound lifetimes, add
719 let substs = Substs::for_item(tcx, def_id,
720 |_, _| tcx.types.re_erased,
721 |def, _| trait_ref.substs().type_for_def(def));
723 // the trait type may have higher-ranked lifetimes in it;
724 // so erase them if they appear, so that we get the type
725 // at some particular call site
726 let substs = tcx.erase_late_bound_regions_and_normalize(&ty::Binder(substs));
728 // It's possible that the method relies on where clauses that
729 // do not hold for this particular set of type parameters.
730 // Note that this method could then never be called, so we
731 // do not want to try and trans it, in that case (see #23435).
732 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
733 if !normalize_and_test_predicates(tcx, predicates.predicates) {
734 debug!("vtable_methods: predicates do not hold");
738 Some((def_id, substs))
744 impl<'tcx,O> Obligation<'tcx,O> {
745 pub fn new(cause: ObligationCause<'tcx>,
746 param_env: ty::ParamEnv<'tcx>,
748 -> Obligation<'tcx, O>
750 Obligation { cause, param_env, recursion_depth: 0, predicate }
753 fn with_depth(cause: ObligationCause<'tcx>,
754 recursion_depth: usize,
755 param_env: ty::ParamEnv<'tcx>,
757 -> Obligation<'tcx, O>
759 Obligation { cause, param_env, recursion_depth, predicate }
762 pub fn misc(span: Span,
763 body_id: ast::NodeId,
764 param_env: ty::ParamEnv<'tcx>,
766 -> Obligation<'tcx, O> {
767 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
770 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
771 Obligation { cause: self.cause.clone(),
772 param_env: self.param_env,
773 recursion_depth: self.recursion_depth,
778 impl<'tcx> ObligationCause<'tcx> {
779 pub fn new(span: Span,
780 body_id: ast::NodeId,
781 code: ObligationCauseCode<'tcx>)
782 -> ObligationCause<'tcx> {
783 ObligationCause { span: span, body_id: body_id, code: code }
786 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
787 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
790 pub fn dummy() -> ObligationCause<'tcx> {
791 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
795 impl<'tcx, N> Vtable<'tcx, N> {
796 pub fn nested_obligations(self) -> Vec<N> {
798 VtableImpl(i) => i.nested,
800 VtableBuiltin(i) => i.nested,
801 VtableAutoImpl(d) => d.nested,
802 VtableClosure(c) => c.nested,
803 VtableGenerator(c) => c.nested,
804 VtableObject(d) => d.nested,
805 VtableFnPointer(d) => d.nested,
809 fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
811 &mut VtableImpl(ref mut i) => &mut i.nested,
812 &mut VtableParam(ref mut n) => n,
813 &mut VtableBuiltin(ref mut i) => &mut i.nested,
814 &mut VtableAutoImpl(ref mut d) => &mut d.nested,
815 &mut VtableGenerator(ref mut c) => &mut c.nested,
816 &mut VtableClosure(ref mut c) => &mut c.nested,
817 &mut VtableObject(ref mut d) => &mut d.nested,
818 &mut VtableFnPointer(ref mut d) => &mut d.nested,
822 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
824 VtableImpl(i) => VtableImpl(VtableImplData {
825 impl_def_id: i.impl_def_id,
827 nested: i.nested.into_iter().map(f).collect(),
829 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
830 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
831 nested: i.nested.into_iter().map(f).collect(),
833 VtableObject(o) => VtableObject(VtableObjectData {
834 upcast_trait_ref: o.upcast_trait_ref,
835 vtable_base: o.vtable_base,
836 nested: o.nested.into_iter().map(f).collect(),
838 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
839 trait_def_id: d.trait_def_id,
840 nested: d.nested.into_iter().map(f).collect(),
842 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
844 nested: p.nested.into_iter().map(f).collect(),
846 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
847 closure_def_id: c.closure_def_id,
849 nested: c.nested.into_iter().map(f).collect(),
851 VtableClosure(c) => VtableClosure(VtableClosureData {
852 closure_def_id: c.closure_def_id,
854 nested: c.nested.into_iter().map(f).collect(),
860 impl<'tcx> FulfillmentError<'tcx> {
861 fn new(obligation: PredicateObligation<'tcx>,
862 code: FulfillmentErrorCode<'tcx>)
863 -> FulfillmentError<'tcx>
865 FulfillmentError { obligation: obligation, code: code }
869 impl<'tcx> TraitObligation<'tcx> {
870 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
871 ty::Binder(self.predicate.skip_binder().self_ty())
875 pub fn provide(providers: &mut ty::maps::Providers) {
876 *providers = ty::maps::Providers {
877 is_object_safe: object_safety::is_object_safe_provider,
878 specialization_graph_of: specialize::specialization_graph_provider,
879 specializes: specialize::specializes,
880 trans_fulfill_obligation: trans::trans_fulfill_obligation,