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::*;
18 use middle::def_id::DefId;
19 use middle::free_region::FreeRegionMap;
21 use middle::ty::{self, Ty, TypeFoldable};
22 use middle::infer::{self, fixup_err_to_string, InferCtxt};
26 use syntax::codemap::{Span, DUMMY_SP};
28 pub use self::error_reporting::TraitErrorKey;
29 pub use self::error_reporting::recursive_type_with_infinite_size_error;
30 pub use self::error_reporting::report_fulfillment_errors;
31 pub use self::error_reporting::report_overflow_error;
32 pub use self::error_reporting::report_overflow_error_cycle;
33 pub use self::error_reporting::report_selection_error;
34 pub use self::error_reporting::report_object_safety_error;
35 pub use self::coherence::orphan_check;
36 pub use self::coherence::overlapping_impls;
37 pub use self::coherence::OrphanCheckErr;
38 pub use self::fulfill::{FulfillmentContext, GlobalFulfilledPredicates, RegionObligation};
39 pub use self::project::MismatchedProjectionTypes;
40 pub use self::project::normalize;
41 pub use self::project::Normalized;
42 pub use self::object_safety::is_object_safe;
43 pub use self::object_safety::astconv_object_safety_violations;
44 pub use self::object_safety::object_safety_violations;
45 pub use self::object_safety::ObjectSafetyViolation;
46 pub use self::object_safety::MethodViolationCode;
47 pub use self::object_safety::is_vtable_safe_method;
48 pub use self::select::EvaluationCache;
49 pub use self::select::SelectionContext;
50 pub use self::select::SelectionCache;
51 pub use self::select::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch};
52 pub use self::select::{MethodMatchedData}; // intentionally don't export variants
53 pub use self::specialize::{Overlap, SpecializationGraph, specializes};
54 pub use self::util::elaborate_predicates;
55 pub use self::util::get_vtable_index_of_object_method;
56 pub use self::util::trait_ref_for_builtin_bound;
57 pub use self::util::predicate_for_trait_def;
58 pub use self::util::supertraits;
59 pub use self::util::Supertraits;
60 pub use self::util::supertrait_def_ids;
61 pub use self::util::SupertraitDefIds;
62 pub use self::util::transitive_bounds;
63 pub use self::util::upcast;
75 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
76 /// which the vtable must be found. The process of finding a vtable is
77 /// called "resolving" the `Obligation`. This process consists of
78 /// either identifying an `impl` (e.g., `impl Eq for int`) that
79 /// provides the required vtable, or else finding a bound that is in
80 /// scope. The eventual result is usually a `Selection` (defined below).
81 #[derive(Clone, PartialEq, Eq)]
82 pub struct Obligation<'tcx, T> {
83 pub cause: ObligationCause<'tcx>,
84 pub recursion_depth: usize,
88 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
89 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
91 /// Why did we incur this obligation? Used for error reporting.
92 #[derive(Clone, Debug, PartialEq, Eq)]
93 pub struct ObligationCause<'tcx> {
96 // The id of the fn body that triggered this obligation. This is
97 // used for region obligations to determine the precise
98 // environment in which the region obligation should be evaluated
99 // (in particular, closures can add new assumptions). See the
100 // field `region_obligations` of the `FulfillmentContext` for more
102 pub body_id: ast::NodeId,
104 pub code: ObligationCauseCode<'tcx>
107 #[derive(Clone, Debug, PartialEq, Eq)]
108 pub enum ObligationCauseCode<'tcx> {
109 /// Not well classified or should be obvious from span.
112 /// This is the trait reference from the given projection
115 /// This is the trait reference from the given projection
116 ProjectionWf(ty::ProjectionTy<'tcx>),
118 /// In an impl of trait X for type Y, type Y must
119 /// also implement all supertraits of X.
120 ItemObligation(DefId),
122 /// A type like `&'a T` is WF only if `T: 'a`.
123 ReferenceOutlivesReferent(Ty<'tcx>),
125 /// Obligation incurred due to an object cast.
126 ObjectCastObligation(/* Object type */ Ty<'tcx>),
128 /// Various cases where expressions must be sized/copy/etc:
129 AssignmentLhsSized, // L = X implies that L is Sized
130 StructInitializerSized, // S { ... } must be Sized
131 VariableType(ast::NodeId), // Type of each variable must be Sized
132 ReturnType, // Return type must be Sized
133 RepeatVec, // [T,..n] --> T must be Copy
135 // Captures of variable the given id by a closure (span is the
136 // span of the closure)
137 ClosureCapture(ast::NodeId, Span, ty::BuiltinBound),
139 // Types of fields (other than the last) in a struct must be sized.
142 // static items must have `Sync` type
145 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
147 ImplDerivedObligation(DerivedObligationCause<'tcx>),
149 CompareImplMethodObligation,
152 #[derive(Clone, Debug, PartialEq, Eq)]
153 pub struct DerivedObligationCause<'tcx> {
154 /// The trait reference of the parent obligation that led to the
155 /// current obligation. Note that only trait obligations lead to
156 /// derived obligations, so we just store the trait reference here
158 parent_trait_ref: ty::PolyTraitRef<'tcx>,
160 /// The parent trait had this cause
161 parent_code: Rc<ObligationCauseCode<'tcx>>
164 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
165 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
166 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
168 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
170 #[derive(Clone,Debug)]
171 pub enum SelectionError<'tcx> {
173 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
174 ty::PolyTraitRef<'tcx>,
175 ty::error::TypeError<'tcx>),
176 TraitNotObjectSafe(DefId),
179 pub struct FulfillmentError<'tcx> {
180 pub obligation: PredicateObligation<'tcx>,
181 pub code: FulfillmentErrorCode<'tcx>
185 pub enum FulfillmentErrorCode<'tcx> {
186 CodeSelectionError(SelectionError<'tcx>),
187 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
191 /// When performing resolution, it is typically the case that there
192 /// can be one of three outcomes:
194 /// - `Ok(Some(r))`: success occurred with result `r`
195 /// - `Ok(None)`: could not definitely determine anything, usually due
196 /// to inconclusive type inference.
197 /// - `Err(e)`: error `e` occurred
198 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
200 /// Given the successful resolution of an obligation, the `Vtable`
201 /// indicates where the vtable comes from. Note that while we call this
202 /// a "vtable", it does not necessarily indicate dynamic dispatch at
203 /// runtime. `Vtable` instances just tell the compiler where to find
204 /// methods, but in generic code those methods are typically statically
205 /// dispatched -- only when an object is constructed is a `Vtable`
206 /// instance reified into an actual vtable.
208 /// For example, the vtable may be tied to a specific impl (case A),
209 /// or it may be relative to some bound that is in scope (case B).
213 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
214 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
215 /// impl Clone for int { ... } // Impl_3
217 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
219 /// mixed: Option<T>) {
221 /// // Case A: Vtable points at a specific impl. Only possible when
222 /// // type is concretely known. If the impl itself has bounded
223 /// // type parameters, Vtable will carry resolutions for those as well:
224 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
226 /// // Case B: Vtable must be provided by caller. This applies when
227 /// // type is a type parameter.
228 /// param.clone(); // VtableParam
230 /// // Case C: A mix of cases A and B.
231 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
235 /// ### The type parameter `N`
237 /// See explanation on `VtableImplData`.
239 pub enum Vtable<'tcx, N> {
240 /// Vtable identifying a particular impl.
241 VtableImpl(VtableImplData<'tcx, N>),
243 /// Vtable for default trait implementations
244 /// This carries the information and nested obligations with regards
245 /// to a default implementation for a trait `Trait`. The nested obligations
246 /// ensure the trait implementation holds for all the constituent types.
247 VtableDefaultImpl(VtableDefaultImplData<N>),
249 /// Successful resolution to an obligation provided by the caller
250 /// for some type parameter. The `Vec<N>` represents the
251 /// obligations incurred from normalizing the where-clause (if
255 /// Virtual calls through an object
256 VtableObject(VtableObjectData<'tcx>),
258 /// Successful resolution for a builtin trait.
259 VtableBuiltin(VtableBuiltinData<N>),
261 /// Vtable automatically generated for a closure. The def ID is the ID
262 /// of the closure expression. This is a `VtableImpl` in spirit, but the
263 /// impl is generated by the compiler and does not appear in the source.
264 VtableClosure(VtableClosureData<'tcx, N>),
266 /// Same as above, but for a fn pointer type with the given signature.
267 VtableFnPointer(ty::Ty<'tcx>),
270 /// Identifies a particular impl in the source, along with a set of
271 /// substitutions from the impl's type/lifetime parameters. The
272 /// `nested` vector corresponds to the nested obligations attached to
273 /// the impl's type parameters.
275 /// The type parameter `N` indicates the type used for "nested
276 /// obligations" that are required by the impl. During type check, this
277 /// is `Obligation`, as one might expect. During trans, however, this
278 /// is `()`, because trans only requires a shallow resolution of an
279 /// impl, and nested obligations are satisfied later.
280 #[derive(Clone, PartialEq, Eq)]
281 pub struct VtableImplData<'tcx, N> {
282 pub impl_def_id: DefId,
283 pub substs: &'tcx subst::Substs<'tcx>,
287 #[derive(Clone, PartialEq, Eq)]
288 pub struct VtableClosureData<'tcx, N> {
289 pub closure_def_id: DefId,
290 pub substs: ty::ClosureSubsts<'tcx>,
291 /// Nested obligations. This can be non-empty if the closure
292 /// signature contains associated types.
297 pub struct VtableDefaultImplData<N> {
298 pub trait_def_id: DefId,
303 pub struct VtableBuiltinData<N> {
307 /// A vtable for some object-safe trait `Foo` automatically derived
308 /// for the object type `Foo`.
309 #[derive(PartialEq,Eq,Clone)]
310 pub struct VtableObjectData<'tcx> {
311 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
312 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
314 /// The vtable is formed by concatenating together the method lists of
315 /// the base object trait and all supertraits; this is the start of
316 /// `upcast_trait_ref`'s methods in that vtable.
317 pub vtable_base: usize
320 /// Creates predicate obligations from the generic bounds.
321 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
322 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
323 -> PredicateObligations<'tcx>
325 util::predicates_for_generics(cause, 0, generic_bounds)
328 /// Determines whether the type `ty` is known to meet `bound` and
329 /// returns true if so. Returns false if `ty` either does not meet
330 /// `bound` or is not known to meet bound (note that this is
331 /// conservative towards *no impl*, which is the opposite of the
332 /// `evaluate` methods).
333 pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
335 bound: ty::BuiltinBound,
339 debug!("type_known_to_meet_builtin_bound(ty={:?}, bound={:?})",
343 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
345 util::predicate_for_builtin_bound(infcx.tcx, cause, bound, 0, ty);
346 let obligation = match obligation {
348 Err(..) => return false
350 let result = SelectionContext::new(infcx)
351 .evaluate_obligation_conservatively(&obligation);
352 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} => {:?}",
355 if result && (ty.has_infer_types() || ty.has_closure_types()) {
356 // Because of inference "guessing", selection can sometimes claim
357 // to succeed while the success requires a guess. To ensure
358 // this function's result remains infallible, we must confirm
359 // that guess. While imperfect, I believe this is sound.
361 let mut fulfill_cx = FulfillmentContext::new();
363 // We can use a dummy node-id here because we won't pay any mind
364 // to region obligations that arise (there shouldn't really be any
366 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
368 fulfill_cx.register_builtin_bound(infcx, ty, bound, cause);
370 // Note: we only assume something is `Copy` if we can
371 // *definitively* show that it implements `Copy`. Otherwise,
372 // assume it is move; linear is always ok.
373 match fulfill_cx.select_all_or_error(infcx) {
375 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} success",
381 debug!("type_known_to_meet_builtin_bound: ty={:?} bound={:?} errors={:?}",
393 // FIXME: this is gonna need to be removed ...
394 /// Normalizes the parameter environment, reporting errors if they occur.
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 // 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 tcx = unnormalized_env.tcx;
415 let span = cause.span;
416 let body_id = cause.body_id;
418 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
421 let predicates: Vec<_> =
422 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
423 .filter(|p| !p.is_global()) // (*)
426 // (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
427 // need to be in the *environment* to be proven, so screen those
428 // out. This is important for the soundness of inter-fn
429 // caching. Note though that we should probably check that these
430 // predicates hold at the point where the environment is
431 // constructed, but I am not currently doing so out of laziness.
434 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
437 let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
439 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(elaborated_env));
440 let predicates = match fully_normalize(&infcx,
442 &infcx.parameter_environment.caller_bounds) {
443 Ok(predicates) => predicates,
445 report_fulfillment_errors(&infcx, &errors);
446 return infcx.parameter_environment; // an unnormalized env is better than nothing
450 debug!("normalize_param_env_or_error: normalized predicates={:?}",
453 let free_regions = FreeRegionMap::new();
454 infcx.resolve_regions_and_report_errors(&free_regions, body_id);
455 let predicates = match infcx.fully_resolve(&predicates) {
456 Ok(predicates) => predicates,
458 // If we encounter a fixup error, it means that some type
459 // variable wound up unconstrained. I actually don't know
460 // if this can happen, and I certainly don't expect it to
461 // happen often, but if it did happen it probably
462 // represents a legitimate failure due to some kind of
463 // unconstrained variable, and it seems better not to ICE,
464 // all things considered.
465 let err_msg = fixup_err_to_string(fixup_err);
466 tcx.sess.span_err(span, &err_msg);
467 return infcx.parameter_environment; // an unnormalized env is better than nothing
471 debug!("normalize_param_env_or_error: resolved predicates={:?}",
474 infcx.parameter_environment.with_caller_bounds(predicates)
477 pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
478 cause: ObligationCause<'tcx>,
480 -> Result<T, Vec<FulfillmentError<'tcx>>>
481 where T : TypeFoldable<'tcx>
483 debug!("fully_normalize(value={:?})", value);
485 let mut selcx = &mut SelectionContext::new(infcx);
486 // FIXME (@jroesch) ISSUE 26721
487 // I'm not sure if this is a bug or not, needs further investigation.
488 // It appears that by reusing the fulfillment_cx here we incur more
489 // obligations and later trip an asssertion on regionck.rs line 337.
491 // The two possibilities I see is:
492 // - normalization is not actually fully happening and we
493 // have a bug else where
494 // - we are adding a duplicate bound into the list causing
495 // its size to change.
497 // I think we should probably land this refactor and then come
498 // back to this is a follow-up patch.
499 let mut fulfill_cx = FulfillmentContext::new();
501 let Normalized { value: normalized_value, obligations } =
502 project::normalize(selcx, cause, value);
503 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
506 for obligation in obligations {
507 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
510 debug!("fully_normalize: select_all_or_error start");
511 match fulfill_cx.select_all_or_error(infcx) {
514 debug!("fully_normalize: error={:?}", e);
518 debug!("fully_normalize: select_all_or_error complete");
519 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
520 debug!("fully_normalize: resolved_value={:?}", resolved_value);
524 impl<'tcx,O> Obligation<'tcx,O> {
525 pub fn new(cause: ObligationCause<'tcx>,
527 -> Obligation<'tcx, O>
529 Obligation { cause: cause,
531 predicate: trait_ref }
534 fn with_depth(cause: ObligationCause<'tcx>,
535 recursion_depth: usize,
537 -> Obligation<'tcx, O>
539 Obligation { cause: cause,
540 recursion_depth: recursion_depth,
541 predicate: trait_ref }
544 pub fn misc(span: Span, body_id: ast::NodeId, trait_ref: O) -> Obligation<'tcx, O> {
545 Obligation::new(ObligationCause::misc(span, body_id), trait_ref)
548 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
549 Obligation { cause: self.cause.clone(),
550 recursion_depth: self.recursion_depth,
555 impl<'tcx> ObligationCause<'tcx> {
556 pub fn new(span: Span,
557 body_id: ast::NodeId,
558 code: ObligationCauseCode<'tcx>)
559 -> ObligationCause<'tcx> {
560 ObligationCause { span: span, body_id: body_id, code: code }
563 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
564 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
567 pub fn dummy() -> ObligationCause<'tcx> {
568 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
572 impl<'tcx, N> Vtable<'tcx, N> {
573 pub fn nested_obligations(self) -> Vec<N> {
575 VtableImpl(i) => i.nested,
577 VtableBuiltin(i) => i.nested,
578 VtableDefaultImpl(d) => d.nested,
579 VtableClosure(c) => c.nested,
580 VtableObject(_) | VtableFnPointer(..) => vec![]
584 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
586 VtableImpl(i) => VtableImpl(VtableImplData {
587 impl_def_id: i.impl_def_id,
589 nested: i.nested.into_iter().map(f).collect()
591 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
592 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
593 nested: i.nested.into_iter().map(f).collect()
595 VtableObject(o) => VtableObject(o),
596 VtableDefaultImpl(d) => VtableDefaultImpl(VtableDefaultImplData {
597 trait_def_id: d.trait_def_id,
598 nested: d.nested.into_iter().map(f).collect()
600 VtableFnPointer(f) => VtableFnPointer(f),
601 VtableClosure(c) => VtableClosure(VtableClosureData {
602 closure_def_id: c.closure_def_id,
604 nested: c.nested.into_iter().map(f).collect(),
610 impl<'tcx> FulfillmentError<'tcx> {
611 fn new(obligation: PredicateObligation<'tcx>,
612 code: FulfillmentErrorCode<'tcx>)
613 -> FulfillmentError<'tcx>
615 FulfillmentError { obligation: obligation, code: code }
619 impl<'tcx> TraitObligation<'tcx> {
620 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
621 ty::Binder(self.predicate.skip_binder().self_ty())