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::overlapping_impls;
32 pub use self::coherence::OrphanCheckErr;
33 pub use self::fulfill::{FulfillmentContext, RegionObligation};
34 pub use self::project::MismatchedProjectionTypes;
35 pub use self::project::normalize;
36 pub use self::project::Normalized;
37 pub use self::object_safety::is_object_safe;
38 pub use self::object_safety::object_safety_violations;
39 pub use self::object_safety::ObjectSafetyViolation;
40 pub use self::object_safety::MethodViolationCode;
41 pub use self::select::SelectionContext;
42 pub use self::select::SelectionCache;
43 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
44 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
45 pub use self::util::elaborate_predicates;
46 pub use self::util::get_vtable_index_of_object_method;
47 pub use self::util::trait_ref_for_builtin_bound;
48 pub use self::util::supertraits;
49 pub use self::util::Supertraits;
50 pub use self::util::transitive_bounds;
51 pub use self::util::upcast;
61 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
62 /// which the vtable must be found. The process of finding a vtable is
63 /// called "resolving" the `Obligation`. This process consists of
64 /// either identifying an `impl` (e.g., `impl Eq for int`) that
65 /// provides the required vtable, or else finding a bound that is in
66 /// scope. The eventual result is usually a `Selection` (defined below).
67 #[derive(Clone, PartialEq, Eq)]
68 pub struct Obligation<'tcx, T> {
69 pub cause: ObligationCause<'tcx>,
70 pub recursion_depth: uint,
74 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
75 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
77 /// Why did we incur this obligation? Used for error reporting.
78 #[derive(Clone, PartialEq, Eq)]
79 pub struct ObligationCause<'tcx> {
82 // The id of the fn body that triggered this obligation. This is
83 // used for region obligations to determine the precise
84 // environment in which the region obligation should be evaluated
85 // (in particular, closures can add new assumptions). See the
86 // field `region_obligations` of the `FulfillmentContext` for more
88 pub body_id: ast::NodeId,
90 pub code: ObligationCauseCode<'tcx>
93 #[derive(Clone, PartialEq, Eq)]
94 pub enum ObligationCauseCode<'tcx> {
95 /// Not well classified or should be obvious from span.
98 /// In an impl of trait X for type Y, type Y must
99 /// also implement all supertraits of X.
100 ItemObligation(ast::DefId),
102 /// Obligation incurred due to an object cast.
103 ObjectCastObligation(/* Object type */ Ty<'tcx>),
105 /// Various cases where expressions must be sized/copy/etc:
106 AssignmentLhsSized, // L = X implies that L is Sized
107 StructInitializerSized, // S { ... } must be Sized
108 VariableType(ast::NodeId), // Type of each variable must be Sized
109 ReturnType, // Return type must be Sized
110 RepeatVec, // [T,..n] --> T must be Copy
112 // Captures of variable the given id by a closure (span is the
113 // span of the closure)
114 ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
116 // Types of fields (other than the last) in a struct must be sized.
119 // Only Sized types can be made into objects
122 // static items must have `Sync` type
126 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
128 ImplDerivedObligation(DerivedObligationCause<'tcx>),
130 CompareImplMethodObligation,
133 #[derive(Clone, PartialEq, Eq)]
134 pub struct DerivedObligationCause<'tcx> {
135 /// The trait reference of the parent obligation that led to the
136 /// current obligation. Note that only trait obligations lead to
137 /// derived obligations, so we just store the trait reference here
139 parent_trait_ref: ty::PolyTraitRef<'tcx>,
141 /// The parent trait had this cause
142 parent_code: Rc<ObligationCauseCode<'tcx>>
145 pub type Obligations<'tcx, O> = subst::VecPerParamSpace<Obligation<'tcx, O>>;
146 pub type PredicateObligations<'tcx> = subst::VecPerParamSpace<PredicateObligation<'tcx>>;
147 pub type TraitObligations<'tcx> = subst::VecPerParamSpace<TraitObligation<'tcx>>;
149 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
151 #[derive(Clone,Debug)]
152 pub enum SelectionError<'tcx> {
155 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
156 ty::PolyTraitRef<'tcx>,
160 pub struct FulfillmentError<'tcx> {
161 pub obligation: PredicateObligation<'tcx>,
162 pub code: FulfillmentErrorCode<'tcx>
166 pub enum FulfillmentErrorCode<'tcx> {
167 CodeSelectionError(SelectionError<'tcx>),
168 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
172 /// When performing resolution, it is typically the case that there
173 /// can be one of three outcomes:
175 /// - `Ok(Some(r))`: success occurred with result `r`
176 /// - `Ok(None)`: could not definitely determine anything, usually due
177 /// to inconclusive type inference.
178 /// - `Err(e)`: error `e` occurred
179 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
181 /// Given the successful resolution of an obligation, the `Vtable`
182 /// indicates where the vtable comes from. Note that while we call this
183 /// a "vtable", it does not necessarily indicate dynamic dispatch at
184 /// runtime. `Vtable` instances just tell the compiler where to find
185 /// methods, but in generic code those methods are typically statically
186 /// dispatched -- only when an object is constructed is a `Vtable`
187 /// instance reified into an actual vtable.
189 /// For example, the vtable may be tied to a specific impl (case A),
190 /// or it may be relative to some bound that is in scope (case B).
194 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
195 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
196 /// impl Clone for int { ... } // Impl_3
198 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
200 /// mixed: Option<T>) {
202 /// // Case A: Vtable points at a specific impl. Only possible when
203 /// // type is concretely known. If the impl itself has bounded
204 /// // type parameters, Vtable will carry resolutions for those as well:
205 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
207 /// // Case B: Vtable must be provided by caller. This applies when
208 /// // type is a type parameter.
209 /// param.clone(); // VtableParam
211 /// // Case C: A mix of cases A and B.
212 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
216 /// ### The type parameter `N`
218 /// See explanation on `VtableImplData`.
219 #[derive(Debug,Clone)]
220 pub enum Vtable<'tcx, N> {
221 /// Vtable identifying a particular impl.
222 VtableImpl(VtableImplData<'tcx, N>),
224 /// Successful resolution to an obligation provided by the caller
225 /// for some type parameter. The `Vec<N>` represents the
226 /// obligations incurred from normalizing the where-clause (if
230 /// Virtual calls through an object
231 VtableObject(VtableObjectData<'tcx>),
233 /// Successful resolution for a builtin trait.
234 VtableBuiltin(VtableBuiltinData<N>),
236 /// Vtable automatically generated for a closure. The def ID is the ID
237 /// of the closure expression. This is a `VtableImpl` in spirit, but the
238 /// impl is generated by the compiler and does not appear in the source.
239 VtableClosure(ast::DefId, subst::Substs<'tcx>),
241 /// Same as above, but for a fn pointer type with the given signature.
242 VtableFnPointer(ty::Ty<'tcx>),
245 /// Identifies a particular impl in the source, along with a set of
246 /// substitutions from the impl's type/lifetime parameters. The
247 /// `nested` vector corresponds to the nested obligations attached to
248 /// the impl's type parameters.
250 /// The type parameter `N` indicates the type used for "nested
251 /// obligations" that are required by the impl. During type check, this
252 /// is `Obligation`, as one might expect. During trans, however, this
253 /// is `()`, because trans only requires a shallow resolution of an
254 /// impl, and nested obligations are satisfied later.
255 #[derive(Clone, PartialEq, Eq)]
256 pub struct VtableImplData<'tcx, N> {
257 pub impl_def_id: ast::DefId,
258 pub substs: subst::Substs<'tcx>,
259 pub nested: subst::VecPerParamSpace<N>
262 #[derive(Debug,Clone)]
263 pub struct VtableBuiltinData<N> {
264 pub nested: subst::VecPerParamSpace<N>
267 /// A vtable for some object-safe trait `Foo` automatically derived
268 /// for the object type `Foo`.
269 #[derive(PartialEq,Eq,Clone)]
270 pub struct VtableObjectData<'tcx> {
271 pub object_ty: Ty<'tcx>,
274 /// Creates predicate obligations from the generic bounds.
275 pub fn predicates_for_generics<'tcx>(tcx: &ty::ctxt<'tcx>,
276 cause: ObligationCause<'tcx>,
277 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
278 -> PredicateObligations<'tcx>
280 util::predicates_for_generics(tcx, cause, 0, generic_bounds)
283 /// Determines whether the type `ty` is known to meet `bound` and
284 /// returns true if so. Returns false if `ty` either does not meet
285 /// `bound` or is not known to meet bound (note that this is
286 /// conservative towards *no impl*, which is the opposite of the
287 /// `evaluate` methods).
288 pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
289 typer: &ty::ClosureTyper<'tcx>,
291 bound: ty::BuiltinBound,
293 -> SelectionResult<'tcx, ()>
295 debug!("type_known_to_meet_builtin_bound(ty={}, bound={:?})",
299 let mut fulfill_cx = FulfillmentContext::new();
301 // We can use a dummy node-id here because we won't pay any mind
302 // to region obligations that arise (there shouldn't really be any
304 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
306 fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
308 // Note: we only assume something is `Copy` if we can
309 // *definitively* show that it implements `Copy`. Otherwise,
310 // assume it is move; linear is always ok.
311 let result = match fulfill_cx.select_all_or_error(infcx, typer) {
312 Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
314 // Check if overflow occurred anywhere and propagate that.
315 if errors.iter().any(
316 |err| match err.code { CodeSelectionError(Overflow) => true, _ => false })
318 return Err(Overflow);
321 // Otherwise, if there were any hard errors, propagate an
322 // arbitrary one of those. If no hard errors at all,
328 CodeAmbiguity => None,
329 CodeSelectionError(ref e) => Some(e.clone()),
330 CodeProjectionError(_) => {
331 infcx.tcx.sess.span_bug(
333 "projection error while selecting?")
340 Some(e) => { Err(e) }
345 debug!("type_known_to_meet_builtin_bound: ty={} bound={:?} result={:?}",
353 pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
354 typer: &ty::ClosureTyper<'tcx>,
356 bound: ty::BuiltinBound,
360 match evaluate_builtin_bound(infcx, typer, ty, bound, span) {
366 // ambiguous: if coherence check was successful, shouldn't
367 // happen, but we might have reported an error and been
368 // soldering on, so just treat this like not implemented
372 span_err!(infcx.tcx.sess, span, E0285,
373 "overflow evaluating whether `{}` is `{}`",
374 ty.user_string(infcx.tcx),
375 bound.user_string(infcx.tcx));
376 suggest_new_overflow_limit(infcx.tcx, span);
380 // other errors: not implemented.
386 pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvironment<'a,'tcx>,
387 cause: ObligationCause<'tcx>)
388 -> ty::ParameterEnvironment<'a,'tcx>
390 match normalize_param_env(&unnormalized_env, cause) {
393 // I'm not wild about reporting errors here; I'd prefer to
394 // have the errors get reported at a defined place (e.g.,
395 // during typeck). Instead I have all parameter
396 // environments, in effect, going through this function
397 // and hence potentially reporting errors. This ensurse of
398 // course that we never forget to normalize (the
399 // alternative seemed like it would involve a lot of
400 // manual invocations of this fn -- and then we'd have to
401 // deal with the errors at each of those sites).
403 // In any case, in practice, typeck constructs all the
404 // parameter environments once for every fn as it goes,
405 // and errors will get reported then; so after typeck we
406 // can be sure that no errors should occur.
407 let infcx = infer::new_infer_ctxt(unnormalized_env.tcx);
408 report_fulfillment_errors(&infcx, &errors);
410 // Normalized failed? use what they gave us, it's better than nothing.
416 pub fn normalize_param_env<'a,'tcx>(param_env: &ty::ParameterEnvironment<'a,'tcx>,
417 cause: ObligationCause<'tcx>)
418 -> Result<ty::ParameterEnvironment<'a,'tcx>,
419 Vec<FulfillmentError<'tcx>>>
421 let tcx = param_env.tcx;
423 debug!("normalize_param_env(param_env={})",
424 param_env.repr(tcx));
426 let infcx = infer::new_infer_ctxt(tcx);
427 let predicates = try!(fully_normalize(&infcx, param_env, cause, ¶m_env.caller_bounds));
429 debug!("normalize_param_env: predicates={}",
430 predicates.repr(tcx));
432 Ok(param_env.with_caller_bounds(predicates))
435 pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
436 closure_typer: &ty::ClosureTyper<'tcx>,
437 cause: ObligationCause<'tcx>,
439 -> Result<T, Vec<FulfillmentError<'tcx>>>
440 where T : TypeFoldable<'tcx> + HasProjectionTypes + Clone + Repr<'tcx>
442 let tcx = closure_typer.tcx();
444 debug!("normalize_param_env(value={})",
447 let mut selcx = &mut SelectionContext::new(infcx, closure_typer);
448 let mut fulfill_cx = FulfillmentContext::new();
449 let Normalized { value: normalized_value, obligations } =
450 project::normalize(selcx, cause, value);
451 debug!("normalize_param_env: normalized_value={} obligations={}",
452 normalized_value.repr(tcx),
453 obligations.repr(tcx));
454 for obligation in obligations {
455 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
457 try!(fulfill_cx.select_all_or_error(infcx, closure_typer));
458 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
459 debug!("normalize_param_env: resolved_value={}",
460 resolved_value.repr(tcx));
464 impl<'tcx,O> Obligation<'tcx,O> {
465 pub fn new(cause: ObligationCause<'tcx>,
467 -> Obligation<'tcx, O>
469 Obligation { cause: cause,
471 predicate: trait_ref }
474 fn with_depth(cause: ObligationCause<'tcx>,
475 recursion_depth: uint,
477 -> Obligation<'tcx, O>
479 Obligation { cause: cause,
480 recursion_depth: recursion_depth,
481 predicate: trait_ref }
484 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
485 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
488 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
489 Obligation { cause: self.cause.clone(),
490 recursion_depth: self.recursion_depth,
495 impl<'tcx> ObligationCause<'tcx> {
496 pub fn new(span: Span,
497 body_id: ast::NodeId,
498 code: ObligationCauseCode<'tcx>)
499 -> ObligationCause<'tcx> {
500 ObligationCause { span: span, body_id: body_id, code: code }
503 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
504 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
507 pub fn dummy() -> ObligationCause<'tcx> {
508 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
512 impl<'tcx, N> Vtable<'tcx, N> {
513 pub fn iter_nested(&self) -> Iter<N> {
515 VtableImpl(ref i) => i.iter_nested(),
516 VtableFnPointer(..) => (&[]).iter(),
517 VtableClosure(..) => (&[]).iter(),
518 VtableParam(ref n) => n.iter(),
519 VtableObject(_) => (&[]).iter(),
520 VtableBuiltin(ref i) => i.iter_nested(),
524 pub fn map_nested<M, F>(&self, op: F) -> Vtable<'tcx, M> where F: FnMut(&N) -> M {
526 VtableImpl(ref i) => VtableImpl(i.map_nested(op)),
527 VtableFnPointer(ref sig) => VtableFnPointer((*sig).clone()),
528 VtableClosure(d, ref s) => VtableClosure(d, s.clone()),
529 VtableParam(ref n) => VtableParam(n.iter().map(op).collect()),
530 VtableObject(ref p) => VtableObject(p.clone()),
531 VtableBuiltin(ref b) => VtableBuiltin(b.map_nested(op)),
535 pub fn map_move_nested<M, F>(self, op: F) -> Vtable<'tcx, M> where
539 VtableImpl(i) => VtableImpl(i.map_move_nested(op)),
540 VtableFnPointer(sig) => VtableFnPointer(sig),
541 VtableClosure(d, s) => VtableClosure(d, s),
542 VtableParam(n) => VtableParam(n.into_iter().map(op).collect()),
543 VtableObject(p) => VtableObject(p),
544 VtableBuiltin(no) => VtableBuiltin(no.map_move_nested(op)),
549 impl<'tcx, N> VtableImplData<'tcx, N> {
550 pub fn iter_nested(&self) -> Iter<N> {
554 pub fn map_nested<M, F>(&self, op: F) -> VtableImplData<'tcx, M> where
558 impl_def_id: self.impl_def_id,
559 substs: self.substs.clone(),
560 nested: self.nested.map(op)
564 pub fn map_move_nested<M, F>(self, op: F) -> VtableImplData<'tcx, M> where
567 let VtableImplData { impl_def_id, substs, nested } = self;
569 impl_def_id: impl_def_id,
571 nested: nested.map_move(op)
576 impl<N> VtableBuiltinData<N> {
577 pub fn iter_nested(&self) -> Iter<N> {
581 pub fn map_nested<M, F>(&self, op: F) -> VtableBuiltinData<M> where F: FnMut(&N) -> M {
583 nested: self.nested.map(op)
587 pub fn map_move_nested<M, F>(self, op: F) -> VtableBuiltinData<M> where
591 nested: self.nested.map_move(op)
596 impl<'tcx> FulfillmentError<'tcx> {
597 fn new(obligation: PredicateObligation<'tcx>,
598 code: FulfillmentErrorCode<'tcx>)
599 -> FulfillmentError<'tcx>
601 FulfillmentError { obligation: obligation, code: code }
604 pub fn is_overflow(&self) -> bool {
606 CodeAmbiguity => false,
607 CodeSelectionError(Overflow) => true,
608 CodeSelectionError(_) => false,
609 CodeProjectionError(_) => false,
614 impl<'tcx> TraitObligation<'tcx> {
615 fn self_ty(&self) -> Ty<'tcx> {
616 self.predicate.0.self_ty()