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 doc.rs.
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
18 use middle::mem_categorization::Typer;
20 use middle::ty::{self, Ty};
21 use middle::infer::InferCtxt;
25 use syntax::codemap::{Span, DUMMY_SP};
26 use util::ppaux::{Repr, UserString};
28 pub use self::error_reporting::report_fulfillment_errors;
29 pub use self::error_reporting::suggest_new_overflow_limit;
30 pub use self::coherence::orphan_check;
31 pub use self::coherence::OrphanCheckErr;
32 pub use self::fulfill::{FulfillmentContext, RegionObligation};
33 pub use self::project::MismatchedProjectionTypes;
34 pub use self::project::normalize;
35 pub use self::project::Normalized;
36 pub use self::object_safety::is_object_safe;
37 pub use self::object_safety::object_safety_violations;
38 pub use self::object_safety::ObjectSafetyViolation;
39 pub use self::object_safety::MethodViolationCode;
40 pub use self::select::SelectionContext;
41 pub use self::select::SelectionCache;
42 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
43 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
44 pub use self::util::elaborate_predicates;
45 pub use self::util::get_vtable_index_of_object_method;
46 pub use self::util::trait_ref_for_builtin_bound;
47 pub use self::util::supertraits;
48 pub use self::util::Supertraits;
49 pub use self::util::transitive_bounds;
50 pub use self::util::upcast;
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).
67 pub struct Obligation<'tcx, T> {
68 pub cause: ObligationCause<'tcx>,
69 pub recursion_depth: uint,
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.
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>
93 pub enum ObligationCauseCode<'tcx> {
94 /// Not well classified or should be obvious from span.
97 /// In an impl of trait X for type Y, type Y must
98 /// also implement all supertraits of X.
99 ItemObligation(ast::DefId),
101 /// Obligation incurred due to an object cast.
102 ObjectCastObligation(/* Object type */ Ty<'tcx>),
104 /// Various cases where expressions must be sized/copy/etc:
105 AssignmentLhsSized, // L = X implies that L is Sized
106 StructInitializerSized, // S { ... } must be Sized
107 VariableType(ast::NodeId), // Type of each variable must be Sized
108 ReturnType, // Return type must be Sized
109 RepeatVec, // [T,..n] --> T must be Copy
111 // Captures of variable the given id by a closure (span is the
112 // span of the closure)
113 ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
115 // Types of fields (other than the last) in a struct must be sized.
118 // Only Sized types can be made into objects
121 // static items must have `Sync` type
124 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
126 ImplDerivedObligation(DerivedObligationCause<'tcx>),
130 pub struct DerivedObligationCause<'tcx> {
131 /// The trait reference of the parent obligation that led to the
132 /// current obligation. Note that only trait obligations lead to
133 /// derived obligations, so we just store the trait reference here
135 parent_trait_ref: ty::PolyTraitRef<'tcx>,
137 /// The parent trait had this cause
138 parent_code: Rc<ObligationCauseCode<'tcx>>
141 pub type Obligations<'tcx, O> = subst::VecPerParamSpace<Obligation<'tcx, O>>;
142 pub type PredicateObligations<'tcx> = subst::VecPerParamSpace<PredicateObligation<'tcx>>;
143 pub type TraitObligations<'tcx> = subst::VecPerParamSpace<TraitObligation<'tcx>>;
145 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
147 #[derive(Clone,Show)]
148 pub enum SelectionError<'tcx> {
151 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
152 ty::PolyTraitRef<'tcx>,
156 pub struct FulfillmentError<'tcx> {
157 pub obligation: PredicateObligation<'tcx>,
158 pub code: FulfillmentErrorCode<'tcx>
162 pub enum FulfillmentErrorCode<'tcx> {
163 CodeSelectionError(SelectionError<'tcx>),
164 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
168 /// When performing resolution, it is typically the case that there
169 /// can be one of three outcomes:
171 /// - `Ok(Some(r))`: success occurred with result `r`
172 /// - `Ok(None)`: could not definitely determine anything, usually due
173 /// to inconclusive type inference.
174 /// - `Err(e)`: error `e` occurred
175 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
177 /// Given the successful resolution of an obligation, the `Vtable`
178 /// indicates where the vtable comes from. Note that while we call this
179 /// a "vtable", it does not necessarily indicate dynamic dispatch at
180 /// runtime. `Vtable` instances just tell the compiler where to find
181 /// methods, but in generic code those methods are typically statically
182 /// dispatched -- only when an object is constructed is a `Vtable`
183 /// instance reified into an actual vtable.
185 /// For example, the vtable may be tied to a specific impl (case A),
186 /// or it may be relative to some bound that is in scope (case B).
190 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
191 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
192 /// impl Clone for int { ... } // Impl_3
194 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
196 /// mixed: Option<T>) {
198 /// // Case A: Vtable points at a specific impl. Only possible when
199 /// // type is concretely known. If the impl itself has bounded
200 /// // type parameters, Vtable will carry resolutions for those as well:
201 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
203 /// // Case B: Vtable must be provided by caller. This applies when
204 /// // type is a type parameter.
205 /// param.clone(); // VtableParam
207 /// // Case C: A mix of cases A and B.
208 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
212 /// ### The type parameter `N`
214 /// See explanation on `VtableImplData`.
215 #[derive(Show,Clone)]
216 pub enum Vtable<'tcx, N> {
217 /// Vtable identifying a particular impl.
218 VtableImpl(VtableImplData<'tcx, N>),
220 /// Successful resolution to an obligation provided by the caller
221 /// for some type parameter. The `Vec<N>` represents the
222 /// obligations incurred from normalizing the where-clause (if
226 /// Virtual calls through an object
227 VtableObject(VtableObjectData<'tcx>),
229 /// Successful resolution for a builtin trait.
230 VtableBuiltin(VtableBuiltinData<N>),
232 /// Vtable automatically generated for an unboxed closure. The def
233 /// ID is the ID of the closure expression. This is a `VtableImpl`
234 /// in spirit, but the impl is generated by the compiler and does
235 /// not appear in the source.
236 VtableUnboxedClosure(ast::DefId, subst::Substs<'tcx>),
238 /// Same as above, but for a fn pointer type with the given signature.
239 VtableFnPointer(ty::Ty<'tcx>),
242 /// Identifies a particular impl in the source, along with a set of
243 /// substitutions from the impl's type/lifetime parameters. The
244 /// `nested` vector corresponds to the nested obligations attached to
245 /// the impl's type parameters.
247 /// The type parameter `N` indicates the type used for "nested
248 /// obligations" that are required by the impl. During type check, this
249 /// is `Obligation`, as one might expect. During trans, however, this
250 /// is `()`, because trans only requires a shallow resolution of an
251 /// impl, and nested obligations are satisfied later.
253 pub struct VtableImplData<'tcx, N> {
254 pub impl_def_id: ast::DefId,
255 pub substs: subst::Substs<'tcx>,
256 pub nested: subst::VecPerParamSpace<N>
259 #[derive(Show,Clone)]
260 pub struct VtableBuiltinData<N> {
261 pub nested: subst::VecPerParamSpace<N>
264 /// A vtable for some object-safe trait `Foo` automatically derived
265 /// for the object type `Foo`.
266 #[derive(PartialEq,Eq,Clone)]
267 pub struct VtableObjectData<'tcx> {
268 pub object_ty: Ty<'tcx>,
271 /// True if there exist types that satisfy both of the two given impls.
272 pub fn overlapping_impls(infcx: &InferCtxt,
273 impl1_def_id: ast::DefId,
274 impl2_def_id: ast::DefId)
277 coherence::impl_can_satisfy(infcx, impl1_def_id, impl2_def_id) &&
278 coherence::impl_can_satisfy(infcx, impl2_def_id, impl1_def_id)
281 /// Creates predicate obligations from the generic bounds.
282 pub fn predicates_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
283 cause: ObligationCause<'tcx>,
284 generic_bounds: &ty::GenericBounds<'tcx>)
285 -> PredicateObligations<'tcx>
287 util::predicates_for_generics(tcx, cause, 0, generic_bounds)
290 /// Determines whether the type `ty` is known to meet `bound` and
291 /// returns true if so. Returns false if `ty` either does not meet
292 /// `bound` or is not known to meet bound (note that this is
293 /// conservative towards *no impl*, which is the opposite of the
294 /// `evaluate` methods).
295 pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
296 typer: &ty::UnboxedClosureTyper<'tcx>,
298 bound: ty::BuiltinBound,
300 -> SelectionResult<'tcx, ()>
302 debug!("type_known_to_meet_builtin_bound(ty={}, bound={:?})",
306 let mut fulfill_cx = FulfillmentContext::new();
308 // We can use a dummy node-id here because we won't pay any mind
309 // to region obligations that arise (there shouldn't really be any
311 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
313 fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
315 // Note: we only assume something is `Copy` if we can
316 // *definitively* show that it implements `Copy`. Otherwise,
317 // assume it is move; linear is always ok.
318 let result = match fulfill_cx.select_all_or_error(infcx, typer) {
319 Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
321 // Check if overflow occurred anywhere and propagate that.
322 if errors.iter().any(
323 |err| match err.code { CodeSelectionError(Overflow) => true, _ => false })
325 return Err(Overflow);
328 // Otherwise, if there were any hard errors, propagate an
329 // arbitrary one of those. If no hard errors at all,
335 CodeAmbiguity => None,
336 CodeSelectionError(ref e) => Some(e.clone()),
337 CodeProjectionError(_) => {
338 infcx.tcx.sess.span_bug(
340 "projection error while selecting?")
347 Some(e) => { Err(e) }
352 debug!("type_known_to_meet_builtin_bound: ty={} bound={:?} result={:?}",
360 pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
361 typer: &ty::UnboxedClosureTyper<'tcx>,
363 bound: ty::BuiltinBound,
367 match evaluate_builtin_bound(infcx, typer, ty, bound, span) {
373 // ambiguous: if coherence check was successful, shouldn't
374 // happen, but we might have reported an error and been
375 // soldering on, so just treat this like not implemented
379 infcx.tcx.sess.span_err(
381 format!("overflow evaluating whether `{}` is `{}`",
382 ty.user_string(infcx.tcx),
383 bound.user_string(infcx.tcx)).as_slice());
384 suggest_new_overflow_limit(infcx.tcx, span);
388 // other errors: not implemented.
394 impl<'tcx,O> Obligation<'tcx,O> {
395 pub fn new(cause: ObligationCause<'tcx>,
397 -> Obligation<'tcx, O>
399 Obligation { cause: cause,
401 predicate: trait_ref }
404 fn with_depth(cause: ObligationCause<'tcx>,
405 recursion_depth: uint,
407 -> Obligation<'tcx, O>
409 Obligation { cause: cause,
410 recursion_depth: recursion_depth,
411 predicate: trait_ref }
414 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
415 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
418 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
419 Obligation { cause: self.cause.clone(),
420 recursion_depth: self.recursion_depth,
425 impl<'tcx> ObligationCause<'tcx> {
426 pub fn new(span: Span,
427 body_id: ast::NodeId,
428 code: ObligationCauseCode<'tcx>)
429 -> ObligationCause<'tcx> {
430 ObligationCause { span: span, body_id: body_id, code: code }
433 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
434 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
437 pub fn dummy() -> ObligationCause<'tcx> {
438 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
442 impl<'tcx, N> Vtable<'tcx, N> {
443 pub fn iter_nested(&self) -> Iter<N> {
445 VtableImpl(ref i) => i.iter_nested(),
446 VtableFnPointer(..) => (&[]).iter(),
447 VtableUnboxedClosure(..) => (&[]).iter(),
448 VtableParam(ref n) => n.iter(),
449 VtableObject(_) => (&[]).iter(),
450 VtableBuiltin(ref i) => i.iter_nested(),
454 pub fn map_nested<M, F>(&self, op: F) -> Vtable<'tcx, M> where F: FnMut(&N) -> M {
456 VtableImpl(ref i) => VtableImpl(i.map_nested(op)),
457 VtableFnPointer(ref sig) => VtableFnPointer((*sig).clone()),
458 VtableUnboxedClosure(d, ref s) => VtableUnboxedClosure(d, s.clone()),
459 VtableParam(ref n) => VtableParam(n.iter().map(op).collect()),
460 VtableObject(ref p) => VtableObject(p.clone()),
461 VtableBuiltin(ref b) => VtableBuiltin(b.map_nested(op)),
465 pub fn map_move_nested<M, F>(self, op: F) -> Vtable<'tcx, M> where
469 VtableImpl(i) => VtableImpl(i.map_move_nested(op)),
470 VtableFnPointer(sig) => VtableFnPointer(sig),
471 VtableUnboxedClosure(d, s) => VtableUnboxedClosure(d, s),
472 VtableParam(n) => VtableParam(n.into_iter().map(op).collect()),
473 VtableObject(p) => VtableObject(p),
474 VtableBuiltin(no) => VtableBuiltin(no.map_move_nested(op)),
479 impl<'tcx, N> VtableImplData<'tcx, N> {
480 pub fn iter_nested(&self) -> Iter<N> {
484 pub fn map_nested<M, F>(&self, op: F) -> VtableImplData<'tcx, M> where
488 impl_def_id: self.impl_def_id,
489 substs: self.substs.clone(),
490 nested: self.nested.map(op)
494 pub fn map_move_nested<M, F>(self, op: F) -> VtableImplData<'tcx, M> where
497 let VtableImplData { impl_def_id, substs, nested } = self;
499 impl_def_id: impl_def_id,
501 nested: nested.map_move(op)
506 impl<N> VtableBuiltinData<N> {
507 pub fn iter_nested(&self) -> Iter<N> {
511 pub fn map_nested<M, F>(&self, op: F) -> VtableBuiltinData<M> where F: FnMut(&N) -> M {
513 nested: self.nested.map(op)
517 pub fn map_move_nested<M, F>(self, op: F) -> VtableBuiltinData<M> where
521 nested: self.nested.map_move(op)
526 impl<'tcx> FulfillmentError<'tcx> {
527 fn new(obligation: PredicateObligation<'tcx>,
528 code: FulfillmentErrorCode<'tcx>)
529 -> FulfillmentError<'tcx>
531 FulfillmentError { obligation: obligation, code: code }
534 pub fn is_overflow(&self) -> bool {
536 CodeAmbiguity => false,
537 CodeSelectionError(Overflow) => true,
538 CodeSelectionError(_) => false,
539 CodeProjectionError(_) => false,
544 impl<'tcx> TraitObligation<'tcx> {
545 fn self_ty(&self) -> Ty<'tcx> {
546 self.predicate.0.self_ty()