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 the Book for more.
13 pub use self::SelectionError::*;
14 pub use self::FulfillmentErrorCode::*;
15 pub use self::Vtable::*;
16 pub use self::ObligationCauseCode::*;
19 use middle::ty::{self, HasProjectionTypes, Ty};
20 use middle::ty_fold::TypeFoldable;
21 use middle::infer::{self, 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).
66 #[derive(Clone, PartialEq, Eq)]
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.
77 #[derive(Clone, 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, PartialEq, Eq)]
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
125 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
127 ImplDerivedObligation(DerivedObligationCause<'tcx>),
129 CompareImplMethodObligation,
132 #[derive(Clone, PartialEq, Eq)]
133 pub struct DerivedObligationCause<'tcx> {
134 /// The trait reference of the parent obligation that led to the
135 /// current obligation. Note that only trait obligations lead to
136 /// derived obligations, so we just store the trait reference here
138 parent_trait_ref: ty::PolyTraitRef<'tcx>,
140 /// The parent trait had this cause
141 parent_code: Rc<ObligationCauseCode<'tcx>>
144 pub type Obligations<'tcx, O> = subst::VecPerParamSpace<Obligation<'tcx, O>>;
145 pub type PredicateObligations<'tcx> = subst::VecPerParamSpace<PredicateObligation<'tcx>>;
146 pub type TraitObligations<'tcx> = subst::VecPerParamSpace<TraitObligation<'tcx>>;
148 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
150 #[derive(Clone,Debug)]
151 pub enum SelectionError<'tcx> {
154 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
155 ty::PolyTraitRef<'tcx>,
159 pub struct FulfillmentError<'tcx> {
160 pub obligation: PredicateObligation<'tcx>,
161 pub code: FulfillmentErrorCode<'tcx>
165 pub enum FulfillmentErrorCode<'tcx> {
166 CodeSelectionError(SelectionError<'tcx>),
167 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
171 /// When performing resolution, it is typically the case that there
172 /// can be one of three outcomes:
174 /// - `Ok(Some(r))`: success occurred with result `r`
175 /// - `Ok(None)`: could not definitely determine anything, usually due
176 /// to inconclusive type inference.
177 /// - `Err(e)`: error `e` occurred
178 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
180 /// Given the successful resolution of an obligation, the `Vtable`
181 /// indicates where the vtable comes from. Note that while we call this
182 /// a "vtable", it does not necessarily indicate dynamic dispatch at
183 /// runtime. `Vtable` instances just tell the compiler where to find
184 /// methods, but in generic code those methods are typically statically
185 /// dispatched -- only when an object is constructed is a `Vtable`
186 /// instance reified into an actual vtable.
188 /// For example, the vtable may be tied to a specific impl (case A),
189 /// or it may be relative to some bound that is in scope (case B).
193 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
194 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
195 /// impl Clone for int { ... } // Impl_3
197 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
199 /// mixed: Option<T>) {
201 /// // Case A: Vtable points at a specific impl. Only possible when
202 /// // type is concretely known. If the impl itself has bounded
203 /// // type parameters, Vtable will carry resolutions for those as well:
204 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
206 /// // Case B: Vtable must be provided by caller. This applies when
207 /// // type is a type parameter.
208 /// param.clone(); // VtableParam
210 /// // Case C: A mix of cases A and B.
211 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
215 /// ### The type parameter `N`
217 /// See explanation on `VtableImplData`.
218 #[derive(Debug,Clone)]
219 pub enum Vtable<'tcx, N> {
220 /// Vtable identifying a particular impl.
221 VtableImpl(VtableImplData<'tcx, N>),
223 /// Successful resolution to an obligation provided by the caller
224 /// for some type parameter. The `Vec<N>` represents the
225 /// obligations incurred from normalizing the where-clause (if
229 /// Virtual calls through an object
230 VtableObject(VtableObjectData<'tcx>),
232 /// Successful resolution for a builtin trait.
233 VtableBuiltin(VtableBuiltinData<N>),
235 /// Vtable automatically generated for a closure. The def ID is the ID
236 /// of the closure expression. This is a `VtableImpl` in spirit, but the
237 /// impl is generated by the compiler and does not appear in the source.
238 VtableClosure(ast::DefId, subst::Substs<'tcx>),
240 /// Same as above, but for a fn pointer type with the given signature.
241 VtableFnPointer(ty::Ty<'tcx>),
244 /// Identifies a particular impl in the source, along with a set of
245 /// substitutions from the impl's type/lifetime parameters. The
246 /// `nested` vector corresponds to the nested obligations attached to
247 /// the impl's type parameters.
249 /// The type parameter `N` indicates the type used for "nested
250 /// obligations" that are required by the impl. During type check, this
251 /// is `Obligation`, as one might expect. During trans, however, this
252 /// is `()`, because trans only requires a shallow resolution of an
253 /// impl, and nested obligations are satisfied later.
254 #[derive(Clone, PartialEq, Eq)]
255 pub struct VtableImplData<'tcx, N> {
256 pub impl_def_id: ast::DefId,
257 pub substs: subst::Substs<'tcx>,
258 pub nested: subst::VecPerParamSpace<N>
261 #[derive(Debug,Clone)]
262 pub struct VtableBuiltinData<N> {
263 pub nested: subst::VecPerParamSpace<N>
266 /// A vtable for some object-safe trait `Foo` automatically derived
267 /// for the object type `Foo`.
268 #[derive(PartialEq,Eq,Clone)]
269 pub struct VtableObjectData<'tcx> {
270 pub object_ty: Ty<'tcx>,
273 /// True if there exist types that satisfy both of the two given impls.
274 pub fn overlapping_impls(infcx: &InferCtxt,
275 impl1_def_id: ast::DefId,
276 impl2_def_id: ast::DefId)
279 coherence::impl_can_satisfy(infcx, impl1_def_id, impl2_def_id) &&
280 coherence::impl_can_satisfy(infcx, impl2_def_id, impl1_def_id)
283 /// Creates predicate obligations from the generic bounds.
284 pub fn predicates_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
285 cause: ObligationCause<'tcx>,
286 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
287 -> PredicateObligations<'tcx>
289 util::predicates_for_generics(tcx, cause, 0, generic_bounds)
292 /// Determines whether the type `ty` is known to meet `bound` and
293 /// returns true if so. Returns false if `ty` either does not meet
294 /// `bound` or is not known to meet bound (note that this is
295 /// conservative towards *no impl*, which is the opposite of the
296 /// `evaluate` methods).
297 pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
298 typer: &ty::ClosureTyper<'tcx>,
300 bound: ty::BuiltinBound,
302 -> SelectionResult<'tcx, ()>
304 debug!("type_known_to_meet_builtin_bound(ty={}, bound={:?})",
308 let mut fulfill_cx = FulfillmentContext::new();
310 // We can use a dummy node-id here because we won't pay any mind
311 // to region obligations that arise (there shouldn't really be any
313 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
315 fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
317 // Note: we only assume something is `Copy` if we can
318 // *definitively* show that it implements `Copy`. Otherwise,
319 // assume it is move; linear is always ok.
320 let result = match fulfill_cx.select_all_or_error(infcx, typer) {
321 Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
323 // Check if overflow occurred anywhere and propagate that.
324 if errors.iter().any(
325 |err| match err.code { CodeSelectionError(Overflow) => true, _ => false })
327 return Err(Overflow);
330 // Otherwise, if there were any hard errors, propagate an
331 // arbitrary one of those. If no hard errors at all,
337 CodeAmbiguity => None,
338 CodeSelectionError(ref e) => Some(e.clone()),
339 CodeProjectionError(_) => {
340 infcx.tcx.sess.span_bug(
342 "projection error while selecting?")
349 Some(e) => { Err(e) }
354 debug!("type_known_to_meet_builtin_bound: ty={} bound={:?} result={:?}",
362 pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
363 typer: &ty::ClosureTyper<'tcx>,
365 bound: ty::BuiltinBound,
369 match evaluate_builtin_bound(infcx, typer, ty, bound, span) {
375 // ambiguous: if coherence check was successful, shouldn't
376 // happen, but we might have reported an error and been
377 // soldering on, so just treat this like not implemented
381 span_err!(infcx.tcx.sess, span, E0285,
382 "overflow evaluating whether `{}` is `{}`",
383 ty.user_string(infcx.tcx),
384 bound.user_string(infcx.tcx));
385 suggest_new_overflow_limit(infcx.tcx, span);
389 // other errors: not implemented.
395 pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvironment<'a,'tcx>,
396 cause: ObligationCause<'tcx>)
397 -> ty::ParameterEnvironment<'a,'tcx>
399 match normalize_param_env(&unnormalized_env, cause) {
402 // I'm not wild about reporting errors here; I'd prefer to
403 // have the errors get reported at a defined place (e.g.,
404 // during typeck). Instead I have all parameter
405 // environments, in effect, going through this function
406 // and hence potentially reporting errors. This ensurse of
407 // course that we never forget to normalize (the
408 // alternative seemed like it would involve a lot of
409 // manual invocations of this fn -- and then we'd have to
410 // deal with the errors at each of those sites).
412 // In any case, in practice, typeck constructs all the
413 // parameter environments once for every fn as it goes,
414 // and errors will get reported then; so after typeck we
415 // can be sure that no errors should occur.
416 let infcx = infer::new_infer_ctxt(unnormalized_env.tcx);
417 report_fulfillment_errors(&infcx, &errors);
419 // Normalized failed? use what they gave us, it's better than nothing.
425 pub fn normalize_param_env<'a,'tcx>(param_env: &ty::ParameterEnvironment<'a,'tcx>,
426 cause: ObligationCause<'tcx>)
427 -> Result<ty::ParameterEnvironment<'a,'tcx>,
428 Vec<FulfillmentError<'tcx>>>
430 let tcx = param_env.tcx;
432 debug!("normalize_param_env(param_env={})",
433 param_env.repr(tcx));
435 let infcx = infer::new_infer_ctxt(tcx);
436 let predicates = try!(fully_normalize(&infcx, param_env, cause, ¶m_env.caller_bounds));
438 debug!("normalize_param_env: predicates={}",
439 predicates.repr(tcx));
441 Ok(param_env.with_caller_bounds(predicates))
444 pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
445 closure_typer: &ty::ClosureTyper<'tcx>,
446 cause: ObligationCause<'tcx>,
448 -> Result<T, Vec<FulfillmentError<'tcx>>>
449 where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr<'tcx>
451 let tcx = closure_typer.tcx();
453 debug!("normalize_param_env(value={})",
456 let mut selcx = &mut SelectionContext::new(infcx, closure_typer);
457 let mut fulfill_cx = FulfillmentContext::new();
458 let Normalized { value: normalized_value, obligations } =
459 project::normalize(selcx, cause, value);
460 debug!("normalize_param_env: normalized_value={} obligations={}",
461 normalized_value.repr(tcx),
462 obligations.repr(tcx));
463 for obligation in obligations {
464 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
466 try!(fulfill_cx.select_all_or_error(infcx, closure_typer));
467 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
468 debug!("normalize_param_env: resolved_value={}",
469 resolved_value.repr(tcx));
473 impl<'tcx,O> Obligation<'tcx,O> {
474 pub fn new(cause: ObligationCause<'tcx>,
476 -> Obligation<'tcx, O>
478 Obligation { cause: cause,
480 predicate: trait_ref }
483 fn with_depth(cause: ObligationCause<'tcx>,
484 recursion_depth: uint,
486 -> Obligation<'tcx, O>
488 Obligation { cause: cause,
489 recursion_depth: recursion_depth,
490 predicate: trait_ref }
493 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
494 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
497 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
498 Obligation { cause: self.cause.clone(),
499 recursion_depth: self.recursion_depth,
504 impl<'tcx> ObligationCause<'tcx> {
505 pub fn new(span: Span,
506 body_id: ast::NodeId,
507 code: ObligationCauseCode<'tcx>)
508 -> ObligationCause<'tcx> {
509 ObligationCause { span: span, body_id: body_id, code: code }
512 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
513 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
516 pub fn dummy() -> ObligationCause<'tcx> {
517 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
521 impl<'tcx, N> Vtable<'tcx, N> {
522 pub fn iter_nested(&self) -> Iter<N> {
524 VtableImpl(ref i) => i.iter_nested(),
525 VtableFnPointer(..) => (&[]).iter(),
526 VtableClosure(..) => (&[]).iter(),
527 VtableParam(ref n) => n.iter(),
528 VtableObject(_) => (&[]).iter(),
529 VtableBuiltin(ref i) => i.iter_nested(),
533 pub fn map_nested<M, F>(&self, op: F) -> Vtable<'tcx, M> where F: FnMut(&N) -> M {
535 VtableImpl(ref i) => VtableImpl(i.map_nested(op)),
536 VtableFnPointer(ref sig) => VtableFnPointer((*sig).clone()),
537 VtableClosure(d, ref s) => VtableClosure(d, s.clone()),
538 VtableParam(ref n) => VtableParam(n.iter().map(op).collect()),
539 VtableObject(ref p) => VtableObject(p.clone()),
540 VtableBuiltin(ref b) => VtableBuiltin(b.map_nested(op)),
544 pub fn map_move_nested<M, F>(self, op: F) -> Vtable<'tcx, M> where
548 VtableImpl(i) => VtableImpl(i.map_move_nested(op)),
549 VtableFnPointer(sig) => VtableFnPointer(sig),
550 VtableClosure(d, s) => VtableClosure(d, s),
551 VtableParam(n) => VtableParam(n.into_iter().map(op).collect()),
552 VtableObject(p) => VtableObject(p),
553 VtableBuiltin(no) => VtableBuiltin(no.map_move_nested(op)),
558 impl<'tcx, N> VtableImplData<'tcx, N> {
559 pub fn iter_nested(&self) -> Iter<N> {
563 pub fn map_nested<M, F>(&self, op: F) -> VtableImplData<'tcx, M> where
567 impl_def_id: self.impl_def_id,
568 substs: self.substs.clone(),
569 nested: self.nested.map(op)
573 pub fn map_move_nested<M, F>(self, op: F) -> VtableImplData<'tcx, M> where
576 let VtableImplData { impl_def_id, substs, nested } = self;
578 impl_def_id: impl_def_id,
580 nested: nested.map_move(op)
585 impl<N> VtableBuiltinData<N> {
586 pub fn iter_nested(&self) -> Iter<N> {
590 pub fn map_nested<M, F>(&self, op: F) -> VtableBuiltinData<M> where F: FnMut(&N) -> M {
592 nested: self.nested.map(op)
596 pub fn map_move_nested<M, F>(self, op: F) -> VtableBuiltinData<M> where
600 nested: self.nested.map_move(op)
605 impl<'tcx> FulfillmentError<'tcx> {
606 fn new(obligation: PredicateObligation<'tcx>,
607 code: FulfillmentErrorCode<'tcx>)
608 -> FulfillmentError<'tcx>
610 FulfillmentError { obligation: obligation, code: code }
613 pub fn is_overflow(&self) -> bool {
615 CodeAmbiguity => false,
616 CodeSelectionError(Overflow) => true,
617 CodeSelectionError(_) => false,
618 CodeProjectionError(_) => false,
623 impl<'tcx> TraitObligation<'tcx> {
624 fn self_ty(&self) -> Ty<'tcx> {
625 self.predicate.0.self_ty()