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, fixup_err_to_string, InferCtxt}
;
25 use syntax
::codemap
::{Span, DUMMY_SP}
;
26 use util
::ppaux
::Repr
;
28 pub use self::error_reporting
::report_fulfillment_errors
;
29 pub use self::error_reporting
::report_overflow_error
;
30 pub use self::error_reporting
::suggest_new_overflow_limit
;
31 pub use self::coherence
::orphan_check
;
32 pub use self::coherence
::overlapping_impls
;
33 pub use self::coherence
::OrphanCheckErr
;
34 pub use self::fulfill
::{FulfillmentContext, RegionObligation}
;
35 pub use self::project
::MismatchedProjectionTypes
;
36 pub use self::project
::normalize
;
37 pub use self::project
::Normalized
;
38 pub use self::object_safety
::is_object_safe
;
39 pub use self::object_safety
::object_safety_violations
;
40 pub use self::object_safety
::ObjectSafetyViolation
;
41 pub use self::object_safety
::MethodViolationCode
;
42 pub use self::object_safety
::is_vtable_safe_method
;
43 pub use self::select
::SelectionContext
;
44 pub use self::select
::SelectionCache
;
45 pub use self::select
::{MethodMatchResult, MethodMatched, MethodAmbiguous, MethodDidNotMatch}
;
46 pub use self::select
::{MethodMatchedData}
; // intentionally don't export variants
47 pub use self::util
::elaborate_predicates
;
48 pub use self::util
::get_vtable_index_of_object_method
;
49 pub use self::util
::trait_ref_for_builtin_bound
;
50 pub use self::util
::supertraits
;
51 pub use self::util
::Supertraits
;
52 pub use self::util
::supertrait_def_ids
;
53 pub use self::util
::SupertraitDefIds
;
54 pub use self::util
::transitive_bounds
;
55 pub use self::util
::upcast
;
65 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
66 /// which the vtable must be found. The process of finding a vtable is
67 /// called "resolving" the `Obligation`. This process consists of
68 /// either identifying an `impl` (e.g., `impl Eq for int`) that
69 /// provides the required vtable, or else finding a bound that is in
70 /// scope. The eventual result is usually a `Selection` (defined below).
71 #[derive(Clone, PartialEq, Eq)]
72 pub struct Obligation
<'tcx
, T
> {
73 pub cause
: ObligationCause
<'tcx
>,
74 pub recursion_depth
: usize,
78 pub type PredicateObligation
<'tcx
> = Obligation
<'tcx
, ty
::Predicate
<'tcx
>>;
79 pub type TraitObligation
<'tcx
> = Obligation
<'tcx
, ty
::PolyTraitPredicate
<'tcx
>>;
81 /// Why did we incur this obligation? Used for error reporting.
82 #[derive(Clone, PartialEq, Eq)]
83 pub struct ObligationCause
<'tcx
> {
86 // The id of the fn body that triggered this obligation. This is
87 // used for region obligations to determine the precise
88 // environment in which the region obligation should be evaluated
89 // (in particular, closures can add new assumptions). See the
90 // field `region_obligations` of the `FulfillmentContext` for more
92 pub body_id
: ast
::NodeId
,
94 pub code
: ObligationCauseCode
<'tcx
>
97 #[derive(Clone, PartialEq, Eq)]
98 pub enum ObligationCauseCode
<'tcx
> {
99 /// Not well classified or should be obvious from span.
102 /// In an impl of trait X for type Y, type Y must
103 /// also implement all supertraits of X.
104 ItemObligation(ast
::DefId
),
106 /// Obligation incurred due to an object cast.
107 ObjectCastObligation(/* Object type */ Ty
<'tcx
>),
109 /// Various cases where expressions must be sized/copy/etc:
110 AssignmentLhsSized
, // L = X implies that L is Sized
111 StructInitializerSized
, // S { ... } must be Sized
112 VariableType(ast
::NodeId
), // Type of each variable must be Sized
113 ReturnType
, // Return type must be Sized
114 RepeatVec
, // [T,..n] --> T must be Copy
116 // Captures of variable the given id by a closure (span is the
117 // span of the closure)
118 ClosureCapture(ast
::NodeId
, Span
, ty
::BuiltinBound
),
120 // Types of fields (other than the last) in a struct must be sized.
123 // Only Sized types can be made into objects
126 // static items must have `Sync` type
130 BuiltinDerivedObligation(DerivedObligationCause
<'tcx
>),
132 ImplDerivedObligation(DerivedObligationCause
<'tcx
>),
134 CompareImplMethodObligation
,
137 #[derive(Clone, PartialEq, Eq)]
138 pub struct DerivedObligationCause
<'tcx
> {
139 /// The trait reference of the parent obligation that led to the
140 /// current obligation. Note that only trait obligations lead to
141 /// derived obligations, so we just store the trait reference here
143 parent_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
145 /// The parent trait had this cause
146 parent_code
: Rc
<ObligationCauseCode
<'tcx
>>
149 pub type Obligations
<'tcx
, O
> = subst
::VecPerParamSpace
<Obligation
<'tcx
, O
>>;
150 pub type PredicateObligations
<'tcx
> = subst
::VecPerParamSpace
<PredicateObligation
<'tcx
>>;
151 pub type TraitObligations
<'tcx
> = subst
::VecPerParamSpace
<TraitObligation
<'tcx
>>;
153 pub type Selection
<'tcx
> = Vtable
<'tcx
, PredicateObligation
<'tcx
>>;
155 #[derive(Clone,Debug)]
156 pub enum SelectionError
<'tcx
> {
158 OutputTypeParameterMismatch(ty
::PolyTraitRef
<'tcx
>,
159 ty
::PolyTraitRef
<'tcx
>,
163 pub struct FulfillmentError
<'tcx
> {
164 pub obligation
: PredicateObligation
<'tcx
>,
165 pub code
: FulfillmentErrorCode
<'tcx
>
169 pub enum FulfillmentErrorCode
<'tcx
> {
170 CodeSelectionError(SelectionError
<'tcx
>),
171 CodeProjectionError(MismatchedProjectionTypes
<'tcx
>),
175 /// When performing resolution, it is typically the case that there
176 /// can be one of three outcomes:
178 /// - `Ok(Some(r))`: success occurred with result `r`
179 /// - `Ok(None)`: could not definitely determine anything, usually due
180 /// to inconclusive type inference.
181 /// - `Err(e)`: error `e` occurred
182 pub type SelectionResult
<'tcx
, T
> = Result
<Option
<T
>, SelectionError
<'tcx
>>;
184 /// Given the successful resolution of an obligation, the `Vtable`
185 /// indicates where the vtable comes from. Note that while we call this
186 /// a "vtable", it does not necessarily indicate dynamic dispatch at
187 /// runtime. `Vtable` instances just tell the compiler where to find
188 /// methods, but in generic code those methods are typically statically
189 /// dispatched -- only when an object is constructed is a `Vtable`
190 /// instance reified into an actual vtable.
192 /// For example, the vtable may be tied to a specific impl (case A),
193 /// or it may be relative to some bound that is in scope (case B).
197 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
198 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
199 /// impl Clone for int { ... } // Impl_3
201 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
203 /// mixed: Option<T>) {
205 /// // Case A: Vtable points at a specific impl. Only possible when
206 /// // type is concretely known. If the impl itself has bounded
207 /// // type parameters, Vtable will carry resolutions for those as well:
208 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
210 /// // Case B: Vtable must be provided by caller. This applies when
211 /// // type is a type parameter.
212 /// param.clone(); // VtableParam
214 /// // Case C: A mix of cases A and B.
215 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
219 /// ### The type parameter `N`
221 /// See explanation on `VtableImplData`.
222 #[derive(Debug,Clone)]
223 pub enum Vtable
<'tcx
, N
> {
224 /// Vtable identifying a particular impl.
225 VtableImpl(VtableImplData
<'tcx
, N
>),
227 /// Vtable for default trait implementations
228 /// This carries the information and nested obligations with regards
229 /// to a default implementation for a trait `Trait`. The nested obligations
230 /// ensure the trait implementation holds for all the constituent types.
231 VtableDefaultImpl(VtableDefaultImplData
<N
>),
233 /// Successful resolution to an obligation provided by the caller
234 /// for some type parameter. The `Vec<N>` represents the
235 /// obligations incurred from normalizing the where-clause (if
239 /// Virtual calls through an object
240 VtableObject(VtableObjectData
<'tcx
>),
242 /// Successful resolution for a builtin trait.
243 VtableBuiltin(VtableBuiltinData
<N
>),
245 /// Vtable automatically generated for a closure. The def ID is the ID
246 /// of the closure expression. This is a `VtableImpl` in spirit, but the
247 /// impl is generated by the compiler and does not appear in the source.
248 VtableClosure(ast
::DefId
, subst
::Substs
<'tcx
>),
250 /// Same as above, but for a fn pointer type with the given signature.
251 VtableFnPointer(ty
::Ty
<'tcx
>),
254 /// Identifies a particular impl in the source, along with a set of
255 /// substitutions from the impl's type/lifetime parameters. The
256 /// `nested` vector corresponds to the nested obligations attached to
257 /// the impl's type parameters.
259 /// The type parameter `N` indicates the type used for "nested
260 /// obligations" that are required by the impl. During type check, this
261 /// is `Obligation`, as one might expect. During trans, however, this
262 /// is `()`, because trans only requires a shallow resolution of an
263 /// impl, and nested obligations are satisfied later.
264 #[derive(Clone, PartialEq, Eq)]
265 pub struct VtableImplData
<'tcx
, N
> {
266 pub impl_def_id
: ast
::DefId
,
267 pub substs
: subst
::Substs
<'tcx
>,
268 pub nested
: subst
::VecPerParamSpace
<N
>
271 #[derive(Debug,Clone)]
272 pub struct VtableDefaultImplData
<N
> {
273 pub trait_def_id
: ast
::DefId
,
277 #[derive(Debug,Clone)]
278 pub struct VtableBuiltinData
<N
> {
279 pub nested
: subst
::VecPerParamSpace
<N
>
282 /// A vtable for some object-safe trait `Foo` automatically derived
283 /// for the object type `Foo`.
284 #[derive(PartialEq,Eq,Clone)]
285 pub struct VtableObjectData
<'tcx
> {
286 /// the object type `Foo`.
287 pub object_ty
: Ty
<'tcx
>,
289 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
290 pub upcast_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
293 /// Creates predicate obligations from the generic bounds.
294 pub fn predicates_for_generics
<'tcx
>(tcx
: &ty
::ctxt
<'tcx
>,
295 cause
: ObligationCause
<'tcx
>,
296 generic_bounds
: &ty
::InstantiatedPredicates
<'tcx
>)
297 -> PredicateObligations
<'tcx
>
299 util
::predicates_for_generics(tcx
, cause
, 0, generic_bounds
)
302 /// Determines whether the type `ty` is known to meet `bound` and
303 /// returns true if so. Returns false if `ty` either does not meet
304 /// `bound` or is not known to meet bound (note that this is
305 /// conservative towards *no impl*, which is the opposite of the
306 /// `evaluate` methods).
307 pub fn evaluate_builtin_bound
<'a
,'tcx
>(infcx
: &InferCtxt
<'a
,'tcx
>,
308 typer
: &ty
::ClosureTyper
<'tcx
>,
310 bound
: ty
::BuiltinBound
,
312 -> SelectionResult
<'tcx
, ()>
314 debug
!("type_known_to_meet_builtin_bound(ty={}, bound={:?})",
318 let mut fulfill_cx
= FulfillmentContext
::new();
320 // We can use a dummy node-id here because we won't pay any mind
321 // to region obligations that arise (there shouldn't really be any
323 let cause
= ObligationCause
::misc(span
, ast
::DUMMY_NODE_ID
);
325 fulfill_cx
.register_builtin_bound(infcx
, ty
, bound
, cause
);
327 // Note: we only assume something is `Copy` if we can
328 // *definitively* show that it implements `Copy`. Otherwise,
329 // assume it is move; linear is always ok.
330 let result
= match fulfill_cx
.select_all_or_error(infcx
, typer
) {
331 Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
333 // If there were any hard errors, propagate an arbitrary
334 // one of those. If no hard errors at all, report
340 CodeAmbiguity
=> None
,
341 CodeSelectionError(ref e
) => Some(e
.clone()),
342 CodeProjectionError(_
) => {
343 infcx
.tcx
.sess
.span_bug(
345 "projection error while selecting?")
352 Some(e
) => { Err(e) }
357 debug
!("type_known_to_meet_builtin_bound: ty={} bound={:?} result={:?}",
365 pub fn type_known_to_meet_builtin_bound
<'a
,'tcx
>(infcx
: &InferCtxt
<'a
,'tcx
>,
366 typer
: &ty
::ClosureTyper
<'tcx
>,
368 bound
: ty
::BuiltinBound
,
372 match evaluate_builtin_bound(infcx
, typer
, ty
, bound
, span
) {
378 // ambiguous: if coherence check was successful, shouldn't
379 // happen, but we might have reported an error and been
380 // soldering on, so just treat this like not implemented
384 // errors: not implemented.
390 /// Normalizes the parameter environment, reporting errors if they occur.
391 pub fn normalize_param_env_or_error
<'a
,'tcx
>(unnormalized_env
: ty
::ParameterEnvironment
<'a
,'tcx
>,
392 cause
: ObligationCause
<'tcx
>)
393 -> ty
::ParameterEnvironment
<'a
,'tcx
>
395 // I'm not wild about reporting errors here; I'd prefer to
396 // have the errors get reported at a defined place (e.g.,
397 // during typeck). Instead I have all parameter
398 // environments, in effect, going through this function
399 // and hence potentially reporting errors. This ensurse of
400 // course that we never forget to normalize (the
401 // alternative seemed like it would involve a lot of
402 // manual invocations of this fn -- and then we'd have to
403 // deal with the errors at each of those sites).
405 // In any case, in practice, typeck constructs all the
406 // parameter environments once for every fn as it goes,
407 // and errors will get reported then; so after typeck we
408 // can be sure that no errors should occur.
410 let tcx
= unnormalized_env
.tcx
;
411 let span
= cause
.span
;
412 let body_id
= cause
.body_id
;
414 debug
!("normalize_param_env_or_error(unnormalized_env={})",
415 unnormalized_env
.repr(tcx
));
417 let infcx
= infer
::new_infer_ctxt(tcx
);
418 let predicates
= match fully_normalize(&infcx
, &unnormalized_env
, cause
,
419 &unnormalized_env
.caller_bounds
) {
420 Ok(predicates
) => predicates
,
422 report_fulfillment_errors(&infcx
, &errors
);
423 return unnormalized_env
; // an unnormalized env is better than nothing
427 infcx
.resolve_regions_and_report_errors(body_id
);
428 let predicates
= match infcx
.fully_resolve(&predicates
) {
429 Ok(predicates
) => predicates
,
431 // If we encounter a fixup error, it means that some type
432 // variable wound up unconstrained. I actually don't know
433 // if this can happen, and I certainly don't expect it to
434 // happen often, but if it did happen it probably
435 // represents a legitimate failure due to some kind of
436 // unconstrained variable, and it seems better not to ICE,
437 // all things considered.
438 let err_msg
= fixup_err_to_string(fixup_err
);
439 tcx
.sess
.span_err(span
, &err_msg
);
440 return unnormalized_env
; // an unnormalized env is better than nothing
444 debug
!("normalize_param_env_or_error: predicates={}",
445 predicates
.repr(tcx
));
447 unnormalized_env
.with_caller_bounds(predicates
)
450 pub fn fully_normalize
<'a
,'tcx
,T
>(infcx
: &InferCtxt
<'a
,'tcx
>,
451 closure_typer
: &ty
::ClosureTyper
<'tcx
>,
452 cause
: ObligationCause
<'tcx
>,
454 -> Result
<T
, Vec
<FulfillmentError
<'tcx
>>>
455 where T
: TypeFoldable
<'tcx
> + HasProjectionTypes
+ Clone
+ Repr
<'tcx
>
457 let tcx
= closure_typer
.tcx();
459 debug
!("normalize_param_env(value={})", value
.repr(tcx
));
461 let mut selcx
= &mut SelectionContext
::new(infcx
, closure_typer
);
462 let mut fulfill_cx
= FulfillmentContext
::new();
463 let Normalized { value: normalized_value, obligations }
=
464 project
::normalize(selcx
, cause
, value
);
465 debug
!("normalize_param_env: normalized_value={} obligations={}",
466 normalized_value
.repr(tcx
),
467 obligations
.repr(tcx
));
468 for obligation
in obligations
{
469 fulfill_cx
.register_predicate_obligation(selcx
.infcx(), obligation
);
471 try
!(fulfill_cx
.select_all_or_error(infcx
, closure_typer
));
472 let resolved_value
= infcx
.resolve_type_vars_if_possible(&normalized_value
);
473 debug
!("normalize_param_env: resolved_value={}", resolved_value
.repr(tcx
));
477 impl<'tcx
,O
> Obligation
<'tcx
,O
> {
478 pub fn new(cause
: ObligationCause
<'tcx
>,
480 -> Obligation
<'tcx
, O
>
482 Obligation
{ cause
: cause
,
484 predicate
: trait_ref
}
487 fn with_depth(cause
: ObligationCause
<'tcx
>,
488 recursion_depth
: usize,
490 -> Obligation
<'tcx
, O
>
492 Obligation
{ cause
: cause
,
493 recursion_depth
: recursion_depth
,
494 predicate
: trait_ref
}
497 pub fn misc(span
: Span
, body_id
: ast
::NodeId
, trait_ref
: O
) -> Obligation
<'tcx
, O
> {
498 Obligation
::new(ObligationCause
::misc(span
, body_id
), trait_ref
)
501 pub fn with
<P
>(&self, value
: P
) -> Obligation
<'tcx
,P
> {
502 Obligation
{ cause
: self.cause
.clone(),
503 recursion_depth
: self.recursion_depth
,
508 impl<'tcx
> ObligationCause
<'tcx
> {
509 pub fn new(span
: Span
,
510 body_id
: ast
::NodeId
,
511 code
: ObligationCauseCode
<'tcx
>)
512 -> ObligationCause
<'tcx
> {
513 ObligationCause { span: span, body_id: body_id, code: code }
516 pub fn misc(span
: Span
, body_id
: ast
::NodeId
) -> ObligationCause
<'tcx
> {
517 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
520 pub fn dummy() -> ObligationCause
<'tcx
> {
521 ObligationCause { span: DUMMY_SP, body_id: 0, code: MiscObligation }
525 impl<'tcx
, N
> Vtable
<'tcx
, N
> {
526 pub fn iter_nested(&self) -> Iter
<N
> {
528 VtableImpl(ref i
) => i
.iter_nested(),
529 VtableParam(ref n
) => n
.iter(),
530 VtableBuiltin(ref i
) => i
.iter_nested(),
532 VtableDefaultImpl(..) | VtableFnPointer(..) |
533 VtableClosure(..) => (&[]).iter(),
537 pub fn map_nested
<M
, F
>(&self, op
: F
) -> Vtable
<'tcx
, M
> where F
: FnMut(&N
) -> M
{
539 VtableImpl(ref i
) => VtableImpl(i
.map_nested(op
)),
540 VtableDefaultImpl(ref t
) => VtableDefaultImpl(t
.map_nested(op
)),
541 VtableFnPointer(ref sig
) => VtableFnPointer((*sig
).clone()),
542 VtableClosure(d
, ref s
) => VtableClosure(d
, s
.clone()),
543 VtableParam(ref n
) => VtableParam(n
.iter().map(op
).collect()),
544 VtableObject(ref p
) => VtableObject(p
.clone()),
545 VtableBuiltin(ref b
) => VtableBuiltin(b
.map_nested(op
)),
549 pub fn map_move_nested
<M
, F
>(self, op
: F
) -> Vtable
<'tcx
, M
> where
553 VtableImpl(i
) => VtableImpl(i
.map_move_nested(op
)),
554 VtableFnPointer(sig
) => VtableFnPointer(sig
),
555 VtableClosure(d
, s
) => VtableClosure(d
, s
),
556 VtableDefaultImpl(t
) => VtableDefaultImpl(t
.map_move_nested(op
)),
557 VtableParam(n
) => VtableParam(n
.into_iter().map(op
).collect()),
558 VtableObject(p
) => VtableObject(p
),
559 VtableBuiltin(no
) => VtableBuiltin(no
.map_move_nested(op
)),
564 impl<'tcx
, N
> VtableImplData
<'tcx
, N
> {
565 pub fn iter_nested(&self) -> Iter
<N
> {
569 pub fn map_nested
<M
, F
>(&self, op
: F
) -> VtableImplData
<'tcx
, M
> where
573 impl_def_id
: self.impl_def_id
,
574 substs
: self.substs
.clone(),
575 nested
: self.nested
.map(op
)
579 pub fn map_move_nested
<M
, F
>(self, op
: F
) -> VtableImplData
<'tcx
, M
> where
582 let VtableImplData { impl_def_id, substs, nested }
= self;
584 impl_def_id
: impl_def_id
,
586 nested
: nested
.map_move(op
)
591 impl<N
> VtableDefaultImplData
<N
> {
592 pub fn iter_nested(&self) -> Iter
<N
> {
596 pub fn map_nested
<M
, F
>(&self, op
: F
) -> VtableDefaultImplData
<M
> where
599 VtableDefaultImplData
{
600 trait_def_id
: self.trait_def_id
,
601 nested
: self.nested
.iter().map(op
).collect()
605 pub fn map_move_nested
<M
, F
>(self, op
: F
) -> VtableDefaultImplData
<M
> where
608 let VtableDefaultImplData { trait_def_id, nested }
= self;
609 VtableDefaultImplData
{
610 trait_def_id
: trait_def_id
,
611 nested
: nested
.into_iter().map(op
).collect()
616 impl<N
> VtableBuiltinData
<N
> {
617 pub fn iter_nested(&self) -> Iter
<N
> {
621 pub fn map_nested
<M
, F
>(&self, op
: F
) -> VtableBuiltinData
<M
> where F
: FnMut(&N
) -> M
{
623 nested
: self.nested
.map(op
)
627 pub fn map_move_nested
<M
, F
>(self, op
: F
) -> VtableBuiltinData
<M
> where
631 nested
: self.nested
.map_move(op
)
636 impl<'tcx
> FulfillmentError
<'tcx
> {
637 fn new(obligation
: PredicateObligation
<'tcx
>,
638 code
: FulfillmentErrorCode
<'tcx
>)
639 -> FulfillmentError
<'tcx
>
641 FulfillmentError { obligation: obligation, code: code }
645 impl<'tcx
> TraitObligation
<'tcx
> {
646 fn self_ty(&self) -> ty
::Binder
<Ty
<'tcx
>> {
647 ty
::Binder(self.predicate
.skip_binder().self_ty())