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::*;
18 use hir::def_id::DefId;
19 use middle::free_region::FreeRegionMap;
21 use ty::{self, Ty, TyCtxt, TypeFoldable};
26 use syntax_pos::{Span, DUMMY_SP};
28 pub use self::error_reporting::TraitErrorKey;
29 pub use self::coherence::orphan_check;
30 pub use self::coherence::overlapping_impls;
31 pub use self::coherence::OrphanCheckErr;
32 pub use self::fulfill::{FulfillmentContext, GlobalFulfilledPredicates, RegionObligation};
33 pub use self::project::MismatchedProjectionTypes;
34 pub use self::project::{normalize, normalize_projection_type, Normalized};
35 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, ProjectionMode};
36 pub use self::object_safety::ObjectSafetyViolation;
37 pub use self::object_safety::MethodViolationCode;
38 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
39 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
40 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
41 pub use self::specialize::{OverlapError, specialization_graph, specializes, translate_substs};
42 pub use self::specialize::{SpecializesCache};
43 pub use self::util::elaborate_predicates;
44 pub use self::util::supertraits;
45 pub use self::util::Supertraits;
46 pub use self::util::supertrait_def_ids;
47 pub use self::util::SupertraitDefIds;
48 pub use self::util::transitive_bounds;
60 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
61 /// which the vtable must be found. The process of finding a vtable is
62 /// called "resolving" the `Obligation`. This process consists of
63 /// either identifying an `impl` (e.g., `impl Eq for int`) that
64 /// provides the required vtable, or else finding a bound that is in
65 /// scope. The eventual result is usually a `Selection` (defined below).
66 #[derive(Clone, PartialEq, Eq)]
67 pub struct Obligation<'tcx, T> {
68 pub cause: ObligationCause<'tcx>,
69 pub recursion_depth: usize,
73 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
74 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
76 /// Why did we incur this obligation? Used for error reporting.
77 #[derive(Clone, Debug, PartialEq, Eq)]
78 pub struct ObligationCause<'tcx> {
81 // The id of the fn body that triggered this obligation. This is
82 // used for region obligations to determine the precise
83 // environment in which the region obligation should be evaluated
84 // (in particular, closures can add new assumptions). See the
85 // field `region_obligations` of the `FulfillmentContext` for more
87 pub body_id: ast::NodeId,
89 pub code: ObligationCauseCode<'tcx>
92 #[derive(Clone, Debug, PartialEq, Eq)]
93 pub enum ObligationCauseCode<'tcx> {
94 /// Not well classified or should be obvious from span.
97 /// A slice or array is WF only if `T: Sized`
100 /// A tuple is WF only if its middle elements are Sized
103 /// This is the trait reference from the given projection
104 ProjectionWf(ty::ProjectionTy<'tcx>),
106 /// In an impl of trait X for type Y, type Y must
107 /// also implement all supertraits of X.
108 ItemObligation(DefId),
110 /// A type like `&'a T` is WF only if `T: 'a`.
111 ReferenceOutlivesReferent(Ty<'tcx>),
113 /// Obligation incurred due to an object cast.
114 ObjectCastObligation(/* Object type */ Ty<'tcx>),
116 /// Various cases where expressions must be sized/copy/etc:
117 AssignmentLhsSized, // L = X implies that L is Sized
118 StructInitializerSized, // S { ... } must be Sized
119 VariableType(ast::NodeId), // Type of each variable must be Sized
120 ReturnType, // Return type must be Sized
121 RepeatVec, // [T,..n] --> T must be Copy
123 // Captures of variable the given id by a closure (span is the
124 // span of the closure)
125 ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
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 CompareImplMethodObligation,
143 #[derive(Clone, Debug, PartialEq, Eq)]
144 pub struct DerivedObligationCause<'tcx> {
145 /// The trait reference of the parent obligation that led to the
146 /// current obligation. Note that only trait obligations lead to
147 /// derived obligations, so we just store the trait reference here
149 parent_trait_ref: ty::PolyTraitRef<'tcx>,
151 /// The parent trait had this cause
152 parent_code: Rc<ObligationCauseCode<'tcx>>
155 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
156 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
157 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
159 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
161 #[derive(Clone,Debug)]
162 pub enum SelectionError<'tcx> {
164 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
165 ty::PolyTraitRef<'tcx>,
166 ty::error::TypeError<'tcx>),
167 TraitNotObjectSafe(DefId),
170 pub struct FulfillmentError<'tcx> {
171 pub obligation: PredicateObligation<'tcx>,
172 pub code: FulfillmentErrorCode<'tcx>
176 pub enum FulfillmentErrorCode<'tcx> {
177 CodeSelectionError(SelectionError<'tcx>),
178 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
182 /// When performing resolution, it is typically the case that there
183 /// can be one of three outcomes:
185 /// - `Ok(Some(r))`: success occurred with result `r`
186 /// - `Ok(None)`: could not definitely determine anything, usually due
187 /// to inconclusive type inference.
188 /// - `Err(e)`: error `e` occurred
189 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
191 /// Given the successful resolution of an obligation, the `Vtable`
192 /// indicates where the vtable comes from. Note that while we call this
193 /// a "vtable", it does not necessarily indicate dynamic dispatch at
194 /// runtime. `Vtable` instances just tell the compiler where to find
195 /// methods, but in generic code those methods are typically statically
196 /// dispatched -- only when an object is constructed is a `Vtable`
197 /// instance reified into an actual vtable.
199 /// For example, the vtable may be tied to a specific impl (case A),
200 /// or it may be relative to some bound that is in scope (case B).
204 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
205 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
206 /// impl Clone for int { ... } // Impl_3
208 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
210 /// mixed: Option<T>) {
212 /// // Case A: Vtable points at a specific impl. Only possible when
213 /// // type is concretely known. If the impl itself has bounded
214 /// // type parameters, Vtable will carry resolutions for those as well:
215 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
217 /// // Case B: Vtable must be provided by caller. This applies when
218 /// // type is a type parameter.
219 /// param.clone(); // VtableParam
221 /// // Case C: A mix of cases A and B.
222 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
226 /// ### The type parameter `N`
228 /// See explanation on `VtableImplData`.
230 pub enum Vtable<'tcx, N> {
231 /// Vtable identifying a particular impl.
232 VtableImpl(VtableImplData<'tcx, N>),
234 /// Vtable for default trait implementations
235 /// This carries the information and nested obligations with regards
236 /// to a default implementation for a trait `Trait`. The nested obligations
237 /// ensure the trait implementation holds for all the constituent types.
238 VtableDefaultImpl(VtableDefaultImplData<N>),
240 /// Successful resolution to an obligation provided by the caller
241 /// for some type parameter. The `Vec<N>` represents the
242 /// obligations incurred from normalizing the where-clause (if
246 /// Virtual calls through an object
247 VtableObject(VtableObjectData<'tcx, N>),
249 /// Successful resolution for a builtin trait.
250 VtableBuiltin(VtableBuiltinData<N>),
252 /// Vtable automatically generated for a closure. The def ID is the ID
253 /// of the closure expression. This is a `VtableImpl` in spirit, but the
254 /// impl is generated by the compiler and does not appear in the source.
255 VtableClosure(VtableClosureData<'tcx, N>),
257 /// Same as above, but for a fn pointer type with the given signature.
258 VtableFnPointer(VtableFnPointerData<'tcx, N>),
261 /// Identifies a particular impl in the source, along with a set of
262 /// substitutions from the impl's type/lifetime parameters. The
263 /// `nested` vector corresponds to the nested obligations attached to
264 /// the impl's type parameters.
266 /// The type parameter `N` indicates the type used for "nested
267 /// obligations" that are required by the impl. During type check, this
268 /// is `Obligation`, as one might expect. During trans, however, this
269 /// is `()`, because trans only requires a shallow resolution of an
270 /// impl, and nested obligations are satisfied later.
271 #[derive(Clone, PartialEq, Eq)]
272 pub struct VtableImplData<'tcx, N> {
273 pub impl_def_id: DefId,
274 pub substs: &'tcx subst::Substs<'tcx>,
278 #[derive(Clone, PartialEq, Eq)]
279 pub struct VtableClosureData<'tcx, N> {
280 pub closure_def_id: DefId,
281 pub substs: ty::ClosureSubsts<'tcx>,
282 /// Nested obligations. This can be non-empty if the closure
283 /// signature contains associated types.
288 pub struct VtableDefaultImplData<N> {
289 pub trait_def_id: DefId,
294 pub struct VtableBuiltinData<N> {
298 /// A vtable for some object-safe trait `Foo` automatically derived
299 /// for the object type `Foo`.
300 #[derive(PartialEq,Eq,Clone)]
301 pub struct VtableObjectData<'tcx, N> {
302 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
303 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
305 /// The vtable is formed by concatenating together the method lists of
306 /// the base object trait and all supertraits; this is the start of
307 /// `upcast_trait_ref`'s methods in that vtable.
308 pub vtable_base: usize,
313 #[derive(Clone, PartialEq, Eq)]
314 pub struct VtableFnPointerData<'tcx, N> {
315 pub fn_ty: ty::Ty<'tcx>,
319 /// Creates predicate obligations from the generic bounds.
320 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
321 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
322 -> PredicateObligations<'tcx>
324 util::predicates_for_generics(cause, 0, generic_bounds)
327 /// Determines whether the type `ty` is known to meet `bound` and
328 /// returns true if so. Returns false if `ty` either does not meet
329 /// `bound` or is not known to meet bound (note that this is
330 /// conservative towards *no impl*, which is the opposite of the
331 /// `evaluate` methods).
332 pub fn type_known_to_meet_builtin_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
334 bound: ty::BuiltinBound,
338 debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})",
342 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
344 infcx.tcx.predicate_for_builtin_bound(cause, bound, 0, ty);
345 let obligation = match obligation {
347 Err(..) => return false
349 let result = SelectionContext::new(infcx)
350 .evaluate_obligation_conservatively(&obligation);
351 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} => {:?}",
354 if result && (ty.has_infer_types() || ty.has_closure_types()) {
355 // Because of inference "guessing", selection can sometimes claim
356 // to succeed while the success requires a guess. To ensure
357 // this function's result remains infallible, we must confirm
358 // that guess. While imperfect, I believe this is sound.
360 let mut fulfill_cx = FulfillmentContext::new();
362 // We can use a dummy node-id here because we won't pay any mind
363 // to region obligations that arise (there shouldn't really be any
365 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
367 fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
369 // Note: we only assume something is `Copy` if we can
370 // *definitively* show that it implements `Copy`. Otherwise,
371 // assume it is move; linear is always ok.
372 match fulfill_cx.select_all_or_error(infcx) {
374 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success",
380 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}",
392 // FIXME: this is gonna need to be removed ...
393 /// Normalizes the parameter environment, reporting errors if they occur.
394 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
395 unnormalized_env: ty::ParameterEnvironment<'tcx>,
396 cause: ObligationCause<'tcx>)
397 -> ty::ParameterEnvironment<'tcx>
399 // I'm not wild about reporting errors here; I'd prefer to
400 // have the errors get reported at a defined place (e.g.,
401 // during typeck). Instead I have all parameter
402 // environments, in effect, going through this function
403 // and hence potentially reporting errors. This ensurse of
404 // course that we never forget to normalize (the
405 // alternative seemed like it would involve a lot of
406 // manual invocations of this fn -- and then we'd have to
407 // deal with the errors at each of those sites).
409 // In any case, in practice, typeck constructs all the
410 // parameter environments once for every fn as it goes,
411 // and errors will get reported then; so after typeck we
412 // can be sure that no errors should occur.
414 let span = cause.span;
415 let body_id = cause.body_id;
417 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
420 let predicates: Vec<_> =
421 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
422 .filter(|p| !p.is_global()) // (*)
425 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
426 // need to be in the *environment* to be proven, so screen those
427 // out. This is important for the soundness of inter-fn
428 // caching. Note though that we should probably check that these
429 // predicates hold at the point where the environment is
430 // constructed, but I am not currently doing so out of laziness.
433 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
436 let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
438 tcx.infer_ctxt(None, Some(elaborated_env), ProjectionMode::AnyFinal).enter(|infcx| {
439 let predicates = match fully_normalize(&infcx, cause,
440 &infcx.parameter_environment.caller_bounds) {
441 Ok(predicates) => predicates,
443 infcx.report_fulfillment_errors(&errors);
444 // An unnormalized env is better than nothing.
445 return infcx.parameter_environment;
449 debug!("normalize_param_env_or_error: normalized predicates={:?}",
452 let free_regions = FreeRegionMap::new();
453 infcx.resolve_regions_and_report_errors(&free_regions, body_id);
454 let predicates = match infcx.fully_resolve(&predicates) {
455 Ok(predicates) => predicates,
457 // If we encounter a fixup error, it means that some type
458 // variable wound up unconstrained. I actually don't know
459 // if this can happen, and I certainly don't expect it to
460 // happen often, but if it did happen it probably
461 // represents a legitimate failure due to some kind of
462 // unconstrained variable, and it seems better not to ICE,
463 // all things considered.
464 tcx.sess.span_err(span, &fixup_err.to_string());
465 // An unnormalized env is better than nothing.
466 return infcx.parameter_environment;
470 let predicates = match tcx.lift_to_global(&predicates) {
471 Some(predicates) => predicates,
472 None => return infcx.parameter_environment
475 debug!("normalize_param_env_or_error: resolved predicates={:?}",
478 infcx.parameter_environment.with_caller_bounds(predicates)
482 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
483 cause: ObligationCause<'tcx>,
485 -> Result<T, Vec<FulfillmentError<'tcx>>>
486 where T : TypeFoldable<'tcx>
488 debug!("fully_normalize(value={:?})", value);
490 let mut selcx = &mut SelectionContext::new(infcx);
491 // FIXME (@jroesch) ISSUE 26721
492 // I'm not sure if this is a bug or not, needs further investigation.
493 // It appears that by reusing the fulfillment_cx here we incur more
494 // obligations and later trip an asssertion on regionck.rs line 337.
496 // The two possibilities I see is:
497 // - normalization is not actually fully happening and we
498 // have a bug else where
499 // - we are adding a duplicate bound into the list causing
500 // its size to change.
502 // I think we should probably land this refactor and then come
503 // back to this is a follow-up patch.
504 let mut fulfill_cx = FulfillmentContext::new();
506 let Normalized { value: normalized_value, obligations } =
507 project::normalize(selcx, cause, value);
508 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
511 for obligation in obligations {
512 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
515 debug!("fully_normalize: select_all_or_error start");
516 match fulfill_cx.select_all_or_error(infcx) {
519 debug!("fully_normalize: error={:?}", e);
523 debug!("fully_normalize: select_all_or_error complete");
524 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
525 debug!("fully_normalize: resolved_value={:?}", resolved_value);
529 impl<'tcx,O> Obligation<'tcx,O> {
530 pub fn new(cause: ObligationCause<'tcx>,
532 -> Obligation<'tcx, O>
534 Obligation { cause: cause,
536 predicate: trait_ref }
539 fn with_depth(cause: ObligationCause<'tcx>,
540 recursion_depth: usize,
542 -> Obligation<'tcx, O>
544 Obligation { cause: cause,
545 recursion_depth: recursion_depth,
546 predicate: trait_ref }
549 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
550 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
553 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
554 Obligation { cause: self.cause.clone(),
555 recursion_depth: self.recursion_depth,
560 impl<'tcx> ObligationCause<'tcx> {
561 pub fn new(span: Span,
562 body_id: ast::NodeId,
563 code: ObligationCauseCode<'tcx>)
564 -> ObligationCause<'tcx> {
565 ObligationCause { span: span, body_id: body_id, code: code }
568 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
569 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
572 pub fn dummy() -> ObligationCause<'tcx> {
573 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
577 impl<'tcx, N> Vtable<'tcx, N> {
578 pub fn nested_obligations(self) -> Vec<N> {
580 VtableImpl(i) => i.nested,
582 VtableBuiltin(i) => i.nested,
583 VtableDefaultImpl(d) => d.nested,
584 VtableClosure(c) => c.nested,
585 VtableObject(d) => d.nested,
586 VtableFnPointer(d) => d.nested,
590 fn nested_obligations_mut(&mut self) -> &mut Vec<N> {
592 &mut VtableImpl(ref mut i) => &mut i.nested,
593 &mut VtableParam(ref mut n) => n,
594 &mut VtableBuiltin(ref mut i) => &mut i.nested,
595 &mut VtableDefaultImpl(ref mut d) => &mut d.nested,
596 &mut VtableClosure(ref mut c) => &mut c.nested,
597 &mut VtableObject(ref mut d) => &mut d.nested,
598 &mut VtableFnPointer(ref mut d) => &mut d.nested,
602 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
604 VtableImpl(i) => VtableImpl(VtableImplData {
605 impl_def_id: i.impl_def_id,
607 nested: i.nested.into_iter().map(f).collect(),
609 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
610 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
611 nested: i.nested.into_iter().map(f).collect(),
613 VtableObject(o) => VtableObject(VtableObjectData {
614 upcast_trait_ref: o.upcast_trait_ref,
615 vtable_base: o.vtable_base,
616 nested: o.nested.into_iter().map(f).collect(),
618 VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
619 trait_def_id: d.trait_def_id,
620 nested: d.nested.into_iter().map(f).collect(),
622 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
624 nested: p.nested.into_iter().map(f).collect(),
626 VtableClosure(c) => VtableClosure(VtableClosureData {
627 closure_def_id: c.closure_def_id,
629 nested: c.nested.into_iter().map(f).collect(),
635 impl<'tcx> FulfillmentError<'tcx> {
636 fn new(obligation: PredicateObligation<'tcx>,
637 code: FulfillmentErrorCode<'tcx>)
638 -> FulfillmentError<'tcx>
640 FulfillmentError { obligation: obligation, code: code }
644 impl<'tcx> TraitObligation<'tcx> {
645 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
646 ty::Binder(self.predicate.skip_binder().self_ty())