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 //! See `README.md` for high-level documentation
12 #![allow(dead_code)] // FIXME -- just temporarily
14 pub use self::MethodMatchResult
::*;
15 pub use self::MethodMatchedData
::*;
16 use self::SelectionCandidate
::*;
17 use self::BuiltinBoundConditions
::*;
18 use self::EvaluationResult
::*;
21 use super::DerivedObligationCause
;
23 use super::project
::{normalize_with_depth, Normalized}
;
24 use super::{PredicateObligation, TraitObligation, ObligationCause}
;
25 use super::report_overflow_error
;
26 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation}
;
27 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch}
;
28 use super::{ObjectCastObligation, Obligation}
;
29 use super::TraitNotObjectSafe
;
30 use super::RFC1214Warning
;
32 use super::SelectionResult
;
33 use super::{VtableBuiltin
, VtableImpl
, VtableParam
, VtableClosure
,
34 VtableFnPointer
, VtableObject
, VtableDefaultImpl
};
35 use super::{VtableImplData
, VtableObjectData
, VtableBuiltinData
,
36 VtableClosureData
, VtableDefaultImplData
};
37 use super::object_safety
;
40 use middle
::def_id
::{DefId, LOCAL_CRATE}
;
42 use middle
::infer
::{InferCtxt, TypeFreshener}
;
43 use middle
::subst
::{Subst, Substs, TypeSpace}
;
44 use middle
::ty
::{self, ToPredicate, RegionEscape, ToPolyTraitRef, Ty, HasTypeFlags}
;
45 use middle
::ty
::fast_reject
;
46 use middle
::ty
::fold
::TypeFoldable
;
47 use middle
::ty
::relate
::TypeRelation
;
49 use std
::cell
::RefCell
;
54 use util
::common
::ErrorReported
;
55 use util
::nodemap
::FnvHashMap
;
57 pub struct SelectionContext
<'cx
, 'tcx
:'cx
> {
58 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
60 /// Freshener used specifically for skolemizing entries on the
61 /// obligation stack. This ensures that all entries on the stack
62 /// at one time will have the same set of skolemized entries,
63 /// which is important for checking for trait bounds that
64 /// recursively require themselves.
65 freshener
: TypeFreshener
<'cx
, 'tcx
>,
67 /// If true, indicates that the evaluation should be conservative
68 /// and consider the possibility of types outside this crate.
69 /// This comes up primarily when resolving ambiguity. Imagine
70 /// there is some trait reference `$0 : Bar` where `$0` is an
71 /// inference variable. If `intercrate` is true, then we can never
72 /// say for sure that this reference is not implemented, even if
73 /// there are *no impls at all for `Bar`*, because `$0` could be
74 /// bound to some type that in a downstream crate that implements
75 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
76 /// though, we set this to false, because we are only interested
77 /// in types that the user could actually have written --- in
78 /// other words, we consider `$0 : Bar` to be unimplemented if
79 /// there is no type that the user could *actually name* that
80 /// would satisfy it. This avoids crippling inference, basically.
85 // A stack that walks back up the stack frame.
86 struct TraitObligationStack
<'prev
, 'tcx
: 'prev
> {
87 obligation
: &'prev TraitObligation
<'tcx
>,
89 /// Trait ref from `obligation` but skolemized with the
90 /// selection-context's freshener. Used to check for recursion.
91 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
93 previous
: TraitObligationStackList
<'prev
, 'tcx
>,
97 pub struct SelectionCache
<'tcx
> {
98 hashmap
: RefCell
<FnvHashMap
<ty
::TraitRef
<'tcx
>,
99 SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>>,
102 pub enum MethodMatchResult
{
103 MethodMatched(MethodMatchedData
),
104 MethodAmbiguous(/* list of impls that could apply */ Vec
<DefId
>),
108 #[derive(Copy, Clone, Debug)]
109 pub enum MethodMatchedData
{
110 // In the case of a precise match, we don't really need to store
111 // how the match was found. So don't.
114 // In the case of a coercion, we need to know the precise impl so
115 // that we can determine the type to which things were coerced.
116 CoerciveMethodMatch(/* impl we matched */ DefId
)
119 /// The selection process begins by considering all impls, where
120 /// clauses, and so forth that might resolve an obligation. Sometimes
121 /// we'll be able to say definitively that (e.g.) an impl does not
122 /// apply to the obligation: perhaps it is defined for `usize` but the
123 /// obligation is for `int`. In that case, we drop the impl out of the
124 /// list. But the other cases are considered *candidates*.
126 /// For selection to succeed, there must be exactly one matching
127 /// candidate. If the obligation is fully known, this is guaranteed
128 /// by coherence. However, if the obligation contains type parameters
129 /// or variables, there may be multiple such impls.
131 /// It is not a real problem if multiple matching impls exist because
132 /// of type variables - it just means the obligation isn't sufficiently
133 /// elaborated. In that case we report an ambiguity, and the caller can
134 /// try again after more type information has been gathered or report a
135 /// "type annotations required" error.
137 /// However, with type parameters, this can be a real problem - type
138 /// parameters don't unify with regular types, but they *can* unify
139 /// with variables from blanket impls, and (unless we know its bounds
140 /// will always be satisfied) picking the blanket impl will be wrong
141 /// for at least *some* substitutions. To make this concrete, if we have
143 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
144 /// impl<T: fmt::Debug> AsDebug for T {
146 /// fn debug(self) -> fmt::Debug { self }
148 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
150 /// we can't just use the impl to resolve the <T as AsDebug> obligation
151 /// - a type from another crate (that doesn't implement fmt::Debug) could
152 /// implement AsDebug.
154 /// Because where-clauses match the type exactly, multiple clauses can
155 /// only match if there are unresolved variables, and we can mostly just
156 /// report this ambiguity in that case. This is still a problem - we can't
157 /// *do anything* with ambiguities that involve only regions. This is issue
160 /// If a single where-clause matches and there are no inference
161 /// variables left, then it definitely matches and we can just select
164 /// In fact, we even select the where-clause when the obligation contains
165 /// inference variables. The can lead to inference making "leaps of logic",
166 /// for example in this situation:
168 /// pub trait Foo<T> { fn foo(&self) -> T; }
169 /// impl<T> Foo<()> for T { fn foo(&self) { } }
170 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
172 /// pub fn foo<T>(t: T) where T: Foo<bool> {
173 /// println!("{:?}", <T as Foo<_>>::foo(&t));
175 /// fn main() { foo(false); }
177 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
178 /// impl and the where-clause. We select the where-clause and unify $0=bool,
179 /// so the program prints "false". However, if the where-clause is omitted,
180 /// the blanket impl is selected, we unify $0=(), and the program prints
183 /// Exactly the same issues apply to projection and object candidates, except
184 /// that we can have both a projection candidate and a where-clause candidate
185 /// for the same obligation. In that case either would do (except that
186 /// different "leaps of logic" would occur if inference variables are
187 /// present), and we just pick the where-clause. This is, for example,
188 /// required for associated types to work in default impls, as the bounds
189 /// are visible both as projection bounds and as where-clauses from the
190 /// parameter environment.
191 #[derive(PartialEq,Eq,Debug,Clone)]
192 enum SelectionCandidate
<'tcx
> {
194 BuiltinCandidate(ty
::BuiltinBound
),
195 ParamCandidate(ty
::PolyTraitRef
<'tcx
>),
196 ImplCandidate(DefId
),
197 DefaultImplCandidate(DefId
),
198 DefaultImplObjectCandidate(DefId
),
200 /// This is a trait matching with a projected type as `Self`, and
201 /// we found an applicable bound in the trait definition.
204 /// Implementation of a `Fn`-family trait by one of the
205 /// anonymous types generated for a `||` expression.
206 ClosureCandidate(/* closure */ DefId
, &'tcx ty
::ClosureSubsts
<'tcx
>),
208 /// Implementation of a `Fn`-family trait by one of the anonymous
209 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
214 BuiltinObjectCandidate
,
216 BuiltinUnsizeCandidate
,
221 struct SelectionCandidateSet
<'tcx
> {
222 // a list of candidates that definitely apply to the current
223 // obligation (meaning: types unify).
224 vec
: Vec
<SelectionCandidate
<'tcx
>>,
226 // if this is true, then there were candidates that might or might
227 // not have applied, but we couldn't tell. This occurs when some
228 // of the input types are type variables, in which case there are
229 // various "builtin" rules that might or might not trigger.
233 enum BuiltinBoundConditions
<'tcx
> {
234 If(ty
::Binder
<Vec
<Ty
<'tcx
>>>),
240 enum EvaluationResult
<'tcx
> {
243 EvaluatedToErr(SelectionError
<'tcx
>),
246 impl<'cx
, 'tcx
> SelectionContext
<'cx
, 'tcx
> {
247 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>)
248 -> SelectionContext
<'cx
, 'tcx
> {
251 freshener
: infcx
.freshener(),
256 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>)
257 -> SelectionContext
<'cx
, 'tcx
> {
260 freshener
: infcx
.freshener(),
265 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
269 pub fn tcx(&self) -> &'cx ty
::ctxt
<'tcx
> {
273 pub fn param_env(&self) -> &'cx ty
::ParameterEnvironment
<'cx
, 'tcx
> {
274 self.infcx
.param_env()
277 pub fn closure_typer(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
281 ///////////////////////////////////////////////////////////////////////////
284 // The selection phase tries to identify *how* an obligation will
285 // be resolved. For example, it will identify which impl or
286 // parameter bound is to be used. The process can be inconclusive
287 // if the self type in the obligation is not fully inferred. Selection
288 // can result in an error in one of two ways:
290 // 1. If no applicable impl or parameter bound can be found.
291 // 2. If the output type parameters in the obligation do not match
292 // those specified by the impl/bound. For example, if the obligation
293 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
294 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
296 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
297 /// type environment by performing unification.
298 pub fn select(&mut self, obligation
: &TraitObligation
<'tcx
>)
299 -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
300 debug
!("select({:?})", obligation
);
301 assert
!(!obligation
.predicate
.has_escaping_regions());
303 let stack
= self.push_stack(TraitObligationStackList
::empty(), obligation
);
304 match try
!(self.candidate_from_obligation(&stack
)) {
306 self.consider_unification_despite_ambiguity(obligation
);
309 Some(candidate
) => Ok(Some(try
!(self.confirm_candidate(obligation
, candidate
)))),
313 /// In the particular case of unboxed closure obligations, we can
314 /// sometimes do some amount of unification for the
315 /// argument/return types even though we can't yet fully match obligation.
316 /// The particular case we are interesting in is an obligation of the form:
320 /// where `C` is an unboxed closure type and `FnFoo` is one of the
321 /// `Fn` traits. Because we know that users cannot write impls for closure types
322 /// themselves, the only way that `C : FnFoo` can fail to match is under two
325 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
326 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
327 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
329 /// In either case, we always know what argument types are
330 /// expected by `C`, no matter what kind of `Fn` trait it
331 /// eventually matches. So we can go ahead and unify the argument
332 /// types, even though the end result is ambiguous.
334 /// Note that this is safe *even if* the trait would never be
335 /// matched (case 2 above). After all, in that case, an error will
336 /// result, so it kind of doesn't matter what we do --- unifying
337 /// the argument types can only be helpful to the user, because
338 /// once they patch up the kind of closure that is expected, the
339 /// argment types won't really change.
340 fn consider_unification_despite_ambiguity(&mut self, obligation
: &TraitObligation
<'tcx
>) {
341 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
342 match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
347 // Is the self-type a closure type? We ignore bindings here
348 // because if it is a closure type, it must be a closure type from
349 // within this current fn, and hence none of the higher-ranked
350 // lifetimes can appear inside the self-type.
351 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
352 let (closure_def_id
, substs
) = match self_ty
.sty
{
353 ty
::TyClosure(id
, ref substs
) => (id
, substs
),
356 assert
!(!substs
.has_escaping_regions());
358 // It is OK to call the unnormalized variant here - this is only
359 // reached for TyClosure: Fn inputs where the closure kind is
360 // still unknown, which should only occur in typeck where the
361 // closure type is already normalized.
362 let closure_trait_ref
= self.closure_trait_ref_unnormalized(obligation
,
366 match self.confirm_poly_trait_refs(obligation
.cause
.clone(),
367 obligation
.predicate
.to_poly_trait_ref(),
370 Err(_
) => { /* Silently ignore errors. */ }
374 ///////////////////////////////////////////////////////////////////////////
377 // Tests whether an obligation can be selected or whether an impl
378 // can be applied to particular types. It skips the "confirmation"
379 // step and hence completely ignores output type parameters.
381 // The result is "true" if the obligation *may* hold and "false" if
382 // we can be sure it does not.
384 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
385 pub fn evaluate_obligation(&mut self,
386 obligation
: &PredicateObligation
<'tcx
>)
389 debug
!("evaluate_obligation({:?})",
392 self.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
396 fn evaluate_builtin_bound_recursively
<'o
>(&mut self,
397 bound
: ty
::BuiltinBound
,
398 previous_stack
: &TraitObligationStack
<'o
, 'tcx
>,
400 -> EvaluationResult
<'tcx
>
403 util
::predicate_for_builtin_bound(
405 previous_stack
.obligation
.cause
.clone(),
407 previous_stack
.obligation
.recursion_depth
+ 1,
412 self.evaluate_predicate_recursively(previous_stack
.list(), &obligation
)
414 Err(ErrorReported
) => {
420 fn evaluate_predicates_recursively
<'a
,'o
,I
>(&mut self,
421 stack
: TraitObligationStackList
<'o
, 'tcx
>,
423 -> EvaluationResult
<'tcx
>
424 where I
: Iterator
<Item
=&'a PredicateObligation
<'tcx
>>, 'tcx
:'a
426 let mut result
= EvaluatedToOk
;
427 for obligation
in predicates
{
428 match self.evaluate_predicate_recursively(stack
, obligation
) {
429 EvaluatedToErr(e
) => { return EvaluatedToErr(e); }
430 EvaluatedToAmbig
=> { result = EvaluatedToAmbig; }
437 fn evaluate_predicate_recursively
<'o
>(&mut self,
438 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
439 obligation
: &PredicateObligation
<'tcx
>)
440 -> EvaluationResult
<'tcx
>
442 debug
!("evaluate_predicate_recursively({:?})",
445 // Check the cache from the tcx of predicates that we know
446 // have been proven elsewhere. This cache only contains
447 // predicates that are global in scope and hence unaffected by
448 // the current environment.
449 let w
= RFC1214Warning(false);
450 if self.tcx().fulfilled_predicates
.borrow().is_duplicate(w
, &obligation
.predicate
) {
451 return EvaluatedToOk
;
454 match obligation
.predicate
{
455 ty
::Predicate
::Trait(ref t
) => {
456 assert
!(!t
.has_escaping_regions());
457 let obligation
= obligation
.with(t
.clone());
458 self.evaluate_obligation_recursively(previous_stack
, &obligation
)
461 ty
::Predicate
::Equate(ref p
) => {
462 let result
= self.infcx
.probe(|_
| {
463 self.infcx
.equality_predicate(obligation
.cause
.span
, p
)
466 Ok(()) => EvaluatedToOk
,
467 Err(_
) => EvaluatedToErr(Unimplemented
),
471 ty
::Predicate
::WellFormed(ty
) => {
472 match ty
::wf
::obligations(self.infcx
, obligation
.cause
.body_id
,
473 ty
, obligation
.cause
.span
,
474 obligation
.cause
.code
.is_rfc1214()) {
476 self.evaluate_predicates_recursively(previous_stack
, obligations
.iter()),
482 ty
::Predicate
::TypeOutlives(..) | ty
::Predicate
::RegionOutlives(..) => {
483 // we do not consider region relationships when
484 // evaluating trait matches
488 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
489 if object_safety
::is_object_safe(self.tcx(), trait_def_id
) {
492 EvaluatedToErr(Unimplemented
)
496 ty
::Predicate
::Projection(ref data
) => {
497 self.infcx
.probe(|_
| {
498 let project_obligation
= obligation
.with(data
.clone());
499 match project
::poly_project_and_unify_type(self, &project_obligation
) {
500 Ok(Some(subobligations
)) => {
501 self.evaluate_predicates_recursively(previous_stack
,
502 subobligations
.iter())
508 EvaluatedToErr(Unimplemented
)
516 fn evaluate_obligation_recursively
<'o
>(&mut self,
517 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
518 obligation
: &TraitObligation
<'tcx
>)
519 -> EvaluationResult
<'tcx
>
521 debug
!("evaluate_obligation_recursively({:?})",
524 let stack
= self.push_stack(previous_stack
, obligation
);
526 let result
= self.evaluate_stack(&stack
);
528 debug
!("result: {:?}", result
);
532 fn evaluate_stack
<'o
>(&mut self,
533 stack
: &TraitObligationStack
<'o
, 'tcx
>)
534 -> EvaluationResult
<'tcx
>
536 // In intercrate mode, whenever any of the types are unbound,
537 // there can always be an impl. Even if there are no impls in
538 // this crate, perhaps the type would be unified with
539 // something from another crate that does provide an impl.
541 // In intracrate mode, we must still be conservative. The reason is
542 // that we want to avoid cycles. Imagine an impl like:
544 // impl<T:Eq> Eq for Vec<T>
546 // and a trait reference like `$0 : Eq` where `$0` is an
547 // unbound variable. When we evaluate this trait-reference, we
548 // will unify `$0` with `Vec<$1>` (for some fresh variable
549 // `$1`), on the condition that `$1 : Eq`. We will then wind
550 // up with many candidates (since that are other `Eq` impls
551 // that apply) and try to winnow things down. This results in
552 // a recursive evaluation that `$1 : Eq` -- as you can
553 // imagine, this is just where we started. To avoid that, we
554 // check for unbound variables and return an ambiguous (hence possible)
555 // match if we've seen this trait before.
557 // This suffices to allow chains like `FnMut` implemented in
558 // terms of `Fn` etc, but we could probably make this more
560 let input_types
= stack
.fresh_trait_ref
.0.input_types
();
561 let unbound_input_types
= input_types
.iter().any(|ty
| ty
.is_fresh());
563 unbound_input_types
&&
565 stack
.iter().skip(1).any(
566 |prev
| self.match_fresh_trait_refs(&stack
.fresh_trait_ref
,
567 &prev
.fresh_trait_ref
)))
569 debug
!("evaluate_stack({:?}) --> unbound argument, recursion --> ambiguous",
570 stack
.fresh_trait_ref
);
571 return EvaluatedToAmbig
;
574 // If there is any previous entry on the stack that precisely
575 // matches this obligation, then we can assume that the
576 // obligation is satisfied for now (still all other conditions
577 // must be met of course). One obvious case this comes up is
578 // marker traits like `Send`. Think of a linked list:
580 // struct List<T> { data: T, next: Option<Box<List<T>>> {
582 // `Box<List<T>>` will be `Send` if `T` is `Send` and
583 // `Option<Box<List<T>>>` is `Send`, and in turn
584 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
587 // Note that we do this comparison using the `fresh_trait_ref`
588 // fields. Because these have all been skolemized using
589 // `self.freshener`, we can be sure that (a) this will not
590 // affect the inferencer state and (b) that if we see two
591 // skolemized types with the same index, they refer to the
592 // same unbound type variable.
595 .skip(1) // skip top-most frame
596 .any(|prev
| stack
.fresh_trait_ref
== prev
.fresh_trait_ref
)
598 debug
!("evaluate_stack({:?}) --> recursive",
599 stack
.fresh_trait_ref
);
600 return EvaluatedToOk
;
603 match self.candidate_from_obligation(stack
) {
604 Ok(Some(c
)) => self.winnow_candidate(stack
, &c
),
605 Ok(None
) => EvaluatedToAmbig
,
606 Err(e
) => EvaluatedToErr(e
),
610 /// Evaluates whether the impl with id `impl_def_id` could be applied to the self type
611 /// `obligation_self_ty`. This can be used either for trait or inherent impls.
612 pub fn evaluate_impl(&mut self,
614 obligation
: &TraitObligation
<'tcx
>)
617 debug
!("evaluate_impl(impl_def_id={:?}, obligation={:?})",
621 self.infcx
.probe(|snapshot
| {
622 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
623 Ok((substs
, skol_map
)) => {
624 let vtable_impl
= self.vtable_impl(impl_def_id
,
626 obligation
.cause
.clone(),
627 obligation
.recursion_depth
+ 1,
630 self.winnow_selection(TraitObligationStackList
::empty(),
631 VtableImpl(vtable_impl
)).may_apply()
640 ///////////////////////////////////////////////////////////////////////////
641 // CANDIDATE ASSEMBLY
643 // The selection process begins by examining all in-scope impls,
644 // caller obligations, and so forth and assembling a list of
645 // candidates. See `README.md` and the `Candidate` type for more
648 fn candidate_from_obligation
<'o
>(&mut self,
649 stack
: &TraitObligationStack
<'o
, 'tcx
>)
650 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
652 // Watch out for overflow. This intentionally bypasses (and does
653 // not update) the cache.
654 let recursion_limit
= self.infcx
.tcx
.sess
.recursion_limit
.get();
655 if stack
.obligation
.recursion_depth
>= recursion_limit
{
656 report_overflow_error(self.infcx(), &stack
.obligation
);
659 // Check the cache. Note that we skolemize the trait-ref
660 // separately rather than using `stack.fresh_trait_ref` -- this
661 // is because we want the unbound variables to be replaced
662 // with fresh skolemized types starting from index 0.
663 let cache_fresh_trait_pred
=
664 self.infcx
.freshen(stack
.obligation
.predicate
.clone());
665 debug
!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
666 cache_fresh_trait_pred
,
668 assert
!(!stack
.obligation
.predicate
.has_escaping_regions());
670 match self.check_candidate_cache(&cache_fresh_trait_pred
) {
672 debug
!("CACHE HIT: cache_fresh_trait_pred={:?}, candidate={:?}",
673 cache_fresh_trait_pred
,
680 // If no match, compute result and insert into cache.
681 let candidate
= self.candidate_from_obligation_no_cache(stack
);
683 if self.should_update_candidate_cache(&cache_fresh_trait_pred
, &candidate
) {
684 debug
!("CACHE MISS: cache_fresh_trait_pred={:?}, candidate={:?}",
685 cache_fresh_trait_pred
, candidate
);
686 self.insert_candidate_cache(cache_fresh_trait_pred
, candidate
.clone());
692 fn candidate_from_obligation_no_cache
<'o
>(&mut self,
693 stack
: &TraitObligationStack
<'o
, 'tcx
>)
694 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
696 if stack
.obligation
.predicate
.0.self_ty().references_error() {
697 return Ok(Some(ErrorCandidate
));
700 if !self.is_knowable(stack
) {
701 debug
!("intercrate not knowable");
705 let candidate_set
= try
!(self.assemble_candidates(stack
));
707 if candidate_set
.ambiguous
{
708 debug
!("candidate set contains ambig");
712 let mut candidates
= candidate_set
.vec
;
714 debug
!("assembled {} candidates for {:?}: {:?}",
719 // At this point, we know that each of the entries in the
720 // candidate set is *individually* applicable. Now we have to
721 // figure out if they contain mutual incompatibilities. This
722 // frequently arises if we have an unconstrained input type --
723 // for example, we are looking for $0:Eq where $0 is some
724 // unconstrained type variable. In that case, we'll get a
725 // candidate which assumes $0 == int, one that assumes $0 ==
726 // usize, etc. This spells an ambiguity.
728 // If there is more than one candidate, first winnow them down
729 // by considering extra conditions (nested obligations and so
730 // forth). We don't winnow if there is exactly one
731 // candidate. This is a relatively minor distinction but it
732 // can lead to better inference and error-reporting. An
733 // example would be if there was an impl:
735 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
737 // and we were to see some code `foo.push_clone()` where `boo`
738 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
739 // we were to winnow, we'd wind up with zero candidates.
740 // Instead, we select the right impl now but report `Bar does
741 // not implement Clone`.
742 if candidates
.len() > 1 {
743 candidates
.retain(|c
| self.winnow_candidate(stack
, c
).may_apply())
746 // If there are STILL multiple candidate, we can further reduce
747 // the list by dropping duplicates.
748 if candidates
.len() > 1 {
750 while i
< candidates
.len() {
752 (0..candidates
.len())
754 .any(|j
| self.candidate_should_be_dropped_in_favor_of(&candidates
[i
],
757 debug
!("Dropping candidate #{}/{}: {:?}",
758 i
, candidates
.len(), candidates
[i
]);
759 candidates
.swap_remove(i
);
761 debug
!("Retaining candidate #{}/{}: {:?}",
762 i
, candidates
.len(), candidates
[i
]);
768 // If there are *STILL* multiple candidates, give up and
770 if candidates
.len() > 1 {
771 debug
!("multiple matches, ambig");
776 // If there are *NO* candidates, that there are no impls --
777 // that we know of, anyway. Note that in the case where there
778 // are unbound type variables within the obligation, it might
779 // be the case that you could still satisfy the obligation
780 // from another crate by instantiating the type variables with
781 // a type from another crate that does have an impl. This case
782 // is checked for in `evaluate_stack` (and hence users
783 // who might care about this case, like coherence, should use
785 if candidates
.is_empty() {
786 return Err(Unimplemented
);
789 // Just one candidate left.
790 let candidate
= candidates
.pop().unwrap();
793 ImplCandidate(def_id
) => {
794 match self.tcx().trait_impl_polarity(def_id
) {
795 Some(hir
::ImplPolarity
::Negative
) => return Err(Unimplemented
),
805 fn is_knowable
<'o
>(&mut self,
806 stack
: &TraitObligationStack
<'o
, 'tcx
>)
809 debug
!("is_knowable(intercrate={})", self.intercrate
);
811 if !self.intercrate
{
815 let obligation
= &stack
.obligation
;
816 let predicate
= self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
818 // ok to skip binder because of the nature of the
819 // trait-ref-is-knowable check, which does not care about
821 let trait_ref
= &predicate
.skip_binder().trait_ref
;
823 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
826 fn pick_candidate_cache(&self) -> &SelectionCache
<'tcx
> {
827 // If there are any where-clauses in scope, then we always use
828 // a cache local to this particular scope. Otherwise, we
829 // switch to a global cache. We used to try and draw
830 // finer-grained distinctions, but that led to a serious of
831 // annoying and weird bugs like #22019 and #18290. This simple
832 // rule seems to be pretty clearly safe and also still retains
833 // a very high hit rate (~95% when compiling rustc).
834 if !self.param_env().caller_bounds
.is_empty() {
835 return &self.param_env().selection_cache
;
838 // Avoid using the master cache during coherence and just rely
839 // on the local cache. This effectively disables caching
840 // during coherence. It is really just a simplification to
841 // avoid us having to fear that coherence results "pollute"
842 // the master cache. Since coherence executes pretty quickly,
843 // it's not worth going to more trouble to increase the
844 // hit-rate I don't think.
846 return &self.param_env().selection_cache
;
849 // Otherwise, we can use the global cache.
850 &self.tcx().selection_cache
853 fn check_candidate_cache(&mut self,
854 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>)
855 -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>
857 let cache
= self.pick_candidate_cache();
858 let hashmap
= cache
.hashmap
.borrow();
859 hashmap
.get(&cache_fresh_trait_pred
.0.trait_ref
).cloned()
862 fn insert_candidate_cache(&mut self,
863 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
864 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
866 let cache
= self.pick_candidate_cache();
867 let mut hashmap
= cache
.hashmap
.borrow_mut();
868 hashmap
.insert(cache_fresh_trait_pred
.0.trait_ref
.clone(), candidate
);
871 fn should_update_candidate_cache(&mut self,
872 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>,
873 candidate
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
876 // In general, it's a good idea to cache results, even
877 // ambiguous ones, to save us some trouble later. But we have
878 // to be careful not to cache results that could be
879 // invalidated later by advances in inference. Normally, this
880 // is not an issue, because any inference variables whose
881 // types are not yet bound are "freshened" in the cache key,
882 // which means that if we later get the same request once that
883 // type variable IS bound, we'll have a different cache key.
884 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
885 // not yet known, we may cache the result as `None`. But if
886 // later `_#0t` is bound to `Bar`, then when we freshen we'll
887 // have `Vec<Bar> : Foo` as the cache key.
889 // HOWEVER, it CAN happen that we get an ambiguity result in
890 // one particular case around closures where the cache key
891 // would not change. That is when the precise types of the
892 // upvars that a closure references have not yet been figured
893 // out (i.e., because it is not yet known if they are captured
894 // by ref, and if by ref, what kind of ref). In these cases,
895 // when matching a builtin bound, we will yield back an
896 // ambiguous result. But the *cache key* is just the closure type,
897 // it doesn't capture the state of the upvar computation.
899 // To avoid this trap, just don't cache ambiguous results if
900 // the self-type contains no inference byproducts (that really
901 // shouldn't happen in other circumstances anyway, given
905 Ok(Some(_
)) | Err(_
) => true,
907 cache_fresh_trait_pred
.0.input_types
().has_infer_types()
912 fn assemble_candidates
<'o
>(&mut self,
913 stack
: &TraitObligationStack
<'o
, 'tcx
>)
914 -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>>
916 let TraitObligationStack { obligation, .. }
= *stack
;
917 let ref obligation
= Obligation
{
918 cause
: obligation
.cause
.clone(),
919 recursion_depth
: obligation
.recursion_depth
,
920 predicate
: self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
)
923 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
924 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
926 // This is somewhat problematic, as the current scheme can't really
927 // handle it turning to be a projection. This does end up as truly
928 // ambiguous in most cases anyway.
930 // Until this is fixed, take the fast path out - this also improves
931 // performance by preventing assemble_candidates_from_impls from
932 // matching every impl for this trait.
933 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
936 let mut candidates
= SelectionCandidateSet
{
941 // Other bounds. Consider both in-scope bounds from fn decl
942 // and applicable impls. There is a certain set of precedence rules here.
944 match self.tcx().lang_items
.to_builtin_kind(obligation
.predicate
.def_id()) {
945 Some(ty
::BoundCopy
) => {
946 debug
!("obligation self ty is {:?}",
947 obligation
.predicate
.0.self_ty());
949 // User-defined copy impls are permitted, but only for
950 // structs and enums.
951 try
!(self.assemble_candidates_from_impls(obligation
, &mut candidates
));
953 // For other types, we'll use the builtin rules.
954 try
!(self.assemble_builtin_bound_candidates(ty
::BoundCopy
,
958 Some(bound @ ty
::BoundSized
) => {
959 // Sized is never implementable by end-users, it is
960 // always automatically computed.
961 try
!(self.assemble_builtin_bound_candidates(bound
,
966 None
if self.tcx().lang_items
.unsize_trait() ==
967 Some(obligation
.predicate
.def_id()) => {
968 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
971 Some(ty
::BoundSend
) |
972 Some(ty
::BoundSync
) |
974 try
!(self.assemble_closure_candidates(obligation
, &mut candidates
));
975 try
!(self.assemble_fn_pointer_candidates(obligation
, &mut candidates
));
976 try
!(self.assemble_candidates_from_impls(obligation
, &mut candidates
));
977 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
981 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
982 try
!(self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
));
983 // Default implementations have lower priority, so we only
984 // consider triggering a default if there is no other impl that can apply.
985 if candidates
.vec
.is_empty() {
986 try
!(self.assemble_candidates_from_default_impls(obligation
, &mut candidates
));
988 debug
!("candidate list size: {}", candidates
.vec
.len());
992 fn assemble_candidates_from_projected_tys(&mut self,
993 obligation
: &TraitObligation
<'tcx
>,
994 candidates
: &mut SelectionCandidateSet
<'tcx
>)
996 debug
!("assemble_candidates_for_projected_tys({:?})", obligation
);
998 // FIXME(#20297) -- just examining the self-type is very simplistic
1000 // before we go into the whole skolemization thing, just
1001 // quickly check if the self-type is a projection at all.
1002 let trait_def_id
= match obligation
.predicate
.0.trait_ref
.self_ty().sty
{
1003 ty
::TyProjection(ref data
) => data
.trait_ref
.def_id
,
1004 ty
::TyInfer(ty
::TyVar(_
)) => {
1005 self.tcx().sess
.span_bug(obligation
.cause
.span
,
1006 "Self=_ should have been handled by assemble_candidates");
1011 debug
!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1014 let result
= self.infcx
.probe(|snapshot
| {
1015 self.match_projection_obligation_against_bounds_from_trait(obligation
,
1020 candidates
.vec
.push(ProjectionCandidate
);
1024 fn match_projection_obligation_against_bounds_from_trait(
1026 obligation
: &TraitObligation
<'tcx
>,
1027 snapshot
: &infer
::CombinedSnapshot
)
1030 let poly_trait_predicate
=
1031 self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
1032 let (skol_trait_predicate
, skol_map
) =
1033 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate
, snapshot
);
1034 debug
!("match_projection_obligation_against_bounds_from_trait: \
1035 skol_trait_predicate={:?} skol_map={:?}",
1036 skol_trait_predicate
,
1039 let projection_trait_ref
= match skol_trait_predicate
.trait_ref
.self_ty().sty
{
1040 ty
::TyProjection(ref data
) => &data
.trait_ref
,
1042 self.tcx().sess
.span_bug(
1043 obligation
.cause
.span
,
1044 &format
!("match_projection_obligation_against_bounds_from_trait() called \
1045 but self-ty not a projection: {:?}",
1046 skol_trait_predicate
.trait_ref
.self_ty()));
1049 debug
!("match_projection_obligation_against_bounds_from_trait: \
1050 projection_trait_ref={:?}",
1051 projection_trait_ref
);
1053 let trait_predicates
= self.tcx().lookup_predicates(projection_trait_ref
.def_id
);
1054 let bounds
= trait_predicates
.instantiate(self.tcx(), projection_trait_ref
.substs
);
1055 debug
!("match_projection_obligation_against_bounds_from_trait: \
1059 let matching_bound
=
1060 util
::elaborate_predicates(self.tcx(), bounds
.predicates
.into_vec())
1063 |bound
| self.infcx
.probe(
1064 |_
| self.match_projection(obligation
,
1066 skol_trait_predicate
.trait_ref
.clone(),
1070 debug
!("match_projection_obligation_against_bounds_from_trait: \
1071 matching_bound={:?}",
1073 match matching_bound
{
1076 // Repeat the successful match, if any, this time outside of a probe.
1077 let result
= self.match_projection(obligation
,
1079 skol_trait_predicate
.trait_ref
.clone(),
1088 fn match_projection(&mut self,
1089 obligation
: &TraitObligation
<'tcx
>,
1090 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1091 skol_trait_ref
: ty
::TraitRef
<'tcx
>,
1092 skol_map
: &infer
::SkolemizationMap
,
1093 snapshot
: &infer
::CombinedSnapshot
)
1096 assert
!(!skol_trait_ref
.has_escaping_regions());
1097 let origin
= infer
::RelateOutputImplTypes(obligation
.cause
.span
);
1098 match self.infcx
.sub_poly_trait_refs(false,
1100 trait_bound
.clone(),
1101 ty
::Binder(skol_trait_ref
.clone())) {
1103 Err(_
) => { return false; }
1106 self.infcx
.leak_check(skol_map
, snapshot
).is_ok()
1109 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1110 /// supplied to find out whether it is listed among them.
1112 /// Never affects inference environment.
1113 fn assemble_candidates_from_caller_bounds
<'o
>(&mut self,
1114 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1115 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1116 -> Result
<(),SelectionError
<'tcx
>>
1118 debug
!("assemble_candidates_from_caller_bounds({:?})",
1122 self.param_env().caller_bounds
1124 .filter_map(|o
| o
.to_opt_poly_trait_ref());
1126 let matching_bounds
=
1128 |bound
| self.evaluate_where_clause(stack
, bound
.clone()).may_apply());
1130 let param_candidates
=
1131 matching_bounds
.map(|bound
| ParamCandidate(bound
));
1133 candidates
.vec
.extend(param_candidates
);
1138 fn evaluate_where_clause
<'o
>(&mut self,
1139 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1140 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
1141 -> EvaluationResult
<'tcx
>
1143 self.infcx().probe(move |_
| {
1144 match self.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1145 Ok(obligations
) => {
1146 self.evaluate_predicates_recursively(stack
.list(), obligations
.iter())
1149 EvaluatedToErr(Unimplemented
)
1155 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1156 /// FnMut<..>` where `X` is a closure type.
1158 /// Note: the type parameters on a closure candidate are modeled as *output* type
1159 /// parameters and hence do not affect whether this trait is a match or not. They will be
1160 /// unified during the confirmation step.
1161 fn assemble_closure_candidates(&mut self,
1162 obligation
: &TraitObligation
<'tcx
>,
1163 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1164 -> Result
<(),SelectionError
<'tcx
>>
1166 let kind
= match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
1168 None
=> { return Ok(()); }
1171 // ok to skip binder because the substs on closure types never
1172 // touch bound regions, they just capture the in-scope
1173 // type/region parameters
1174 let self_ty
= *obligation
.self_ty().skip_binder();
1175 let (closure_def_id
, substs
) = match self_ty
.sty
{
1176 ty
::TyClosure(id
, ref substs
) => (id
, substs
),
1177 ty
::TyInfer(ty
::TyVar(_
)) => {
1178 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
1179 candidates
.ambiguous
= true;
1182 _
=> { return Ok(()); }
1185 debug
!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1190 match self.infcx
.closure_kind(closure_def_id
) {
1191 Some(closure_kind
) => {
1192 debug
!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind
);
1193 if closure_kind
.extends(kind
) {
1194 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
));
1198 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
1199 candidates
.ambiguous
= true;
1206 /// Implement one of the `Fn()` family for a fn pointer.
1207 fn assemble_fn_pointer_candidates(&mut self,
1208 obligation
: &TraitObligation
<'tcx
>,
1209 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1210 -> Result
<(),SelectionError
<'tcx
>>
1212 // We provide impl of all fn traits for fn pointers.
1213 if self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.def_id()).is_none() {
1217 // ok to skip binder because what we are inspecting doesn't involve bound regions
1218 let self_ty
= *obligation
.self_ty().skip_binder();
1220 ty
::TyInfer(ty
::TyVar(_
)) => {
1221 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
1222 candidates
.ambiguous
= true; // could wind up being a fn() type
1225 // provide an impl, but only for suitable `fn` pointers
1226 ty
::TyBareFn(_
, &ty
::BareFnTy
{
1227 unsafety
: hir
::Unsafety
::Normal
,
1229 sig
: ty
::Binder(ty
::FnSig
{
1231 output
: ty
::FnConverging(_
),
1235 candidates
.vec
.push(FnPointerCandidate
);
1244 /// Search for impls that might apply to `obligation`.
1245 fn assemble_candidates_from_impls(&mut self,
1246 obligation
: &TraitObligation
<'tcx
>,
1247 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1248 -> Result
<(), SelectionError
<'tcx
>>
1250 debug
!("assemble_candidates_from_impls(obligation={:?})", obligation
);
1252 let def
= self.tcx().lookup_trait_def(obligation
.predicate
.def_id());
1254 def
.for_each_relevant_impl(
1256 obligation
.predicate
.0.trait_ref
.self_ty(),
1258 self.infcx
.probe(|snapshot
| {
1259 if let Ok(_
) = self.match_impl(impl_def_id
, obligation
, snapshot
) {
1260 candidates
.vec
.push(ImplCandidate(impl_def_id
));
1269 fn assemble_candidates_from_default_impls(&mut self,
1270 obligation
: &TraitObligation
<'tcx
>,
1271 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1272 -> Result
<(), SelectionError
<'tcx
>>
1274 // OK to skip binder here because the tests we do below do not involve bound regions
1275 let self_ty
= *obligation
.self_ty().skip_binder();
1276 debug
!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty
);
1278 let def_id
= obligation
.predicate
.def_id();
1280 if self.tcx().trait_has_default_impl(def_id
) {
1282 ty
::TyTrait(..) => {
1283 // For object types, we don't know what the closed
1284 // over types are. For most traits, this means we
1285 // conservatively say nothing; a candidate may be
1286 // added by `assemble_candidates_from_object_ty`.
1287 // However, for the kind of magic reflect trait,
1288 // we consider it to be implemented even for
1289 // object types, because it just lets you reflect
1290 // onto the object type, not into the object's
1292 if self.tcx().has_attr(def_id
, "rustc_reflect_like") {
1293 candidates
.vec
.push(DefaultImplObjectCandidate(def_id
));
1297 ty
::TyProjection(..) => {
1298 // In these cases, we don't know what the actual
1299 // type is. Therefore, we cannot break it down
1300 // into its constituent types. So we don't
1301 // consider the `..` impl but instead just add no
1302 // candidates: this means that typeck will only
1303 // succeed if there is another reason to believe
1304 // that this obligation holds. That could be a
1305 // where-clause or, in the case of an object type,
1306 // it could be that the object type lists the
1307 // trait (e.g. `Foo+Send : Send`). See
1308 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1309 // for an example of a test case that exercises
1312 ty
::TyInfer(ty
::TyVar(_
)) => {
1313 // the defaulted impl might apply, we don't know
1314 candidates
.ambiguous
= true;
1317 candidates
.vec
.push(DefaultImplCandidate(def_id
.clone()))
1325 /// Search for impls that might apply to `obligation`.
1326 fn assemble_candidates_from_object_ty(&mut self,
1327 obligation
: &TraitObligation
<'tcx
>,
1328 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1330 debug
!("assemble_candidates_from_object_ty(self_ty={:?})",
1331 obligation
.self_ty().skip_binder());
1333 // Object-safety candidates are only applicable to object-safe
1334 // traits. Including this check is useful because it helps
1335 // inference in cases of traits like `BorrowFrom`, which are
1336 // not object-safe, and which rely on being able to infer the
1337 // self-type from one of the other inputs. Without this check,
1338 // these cases wind up being considered ambiguous due to a
1339 // (spurious) ambiguity introduced here.
1340 let predicate_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
1341 if !object_safety
::is_object_safe(self.tcx(), predicate_trait_ref
.def_id()) {
1345 self.infcx
.commit_if_ok(|snapshot
| {
1347 self.infcx().skolemize_late_bound_regions(&obligation
.self_ty(), snapshot
);
1348 let poly_trait_ref
= match self_ty
.sty
{
1349 ty
::TyTrait(ref data
) => {
1350 match self.tcx().lang_items
.to_builtin_kind(obligation
.predicate
.def_id()) {
1351 Some(bound @ ty
::BoundSend
) | Some(bound @ ty
::BoundSync
) => {
1352 if data
.bounds
.builtin_bounds
.contains(&bound
) {
1353 debug
!("assemble_candidates_from_object_ty: matched builtin bound, \
1354 pushing candidate");
1355 candidates
.vec
.push(BuiltinObjectCandidate
);
1362 data
.principal_trait_ref_with_self_ty(self.tcx(), self_ty
)
1364 ty
::TyInfer(ty
::TyVar(_
)) => {
1365 debug
!("assemble_candidates_from_object_ty: ambiguous");
1366 candidates
.ambiguous
= true; // could wind up being an object type
1374 debug
!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1377 // Count only those upcast versions that match the trait-ref
1378 // we are looking for. Specifically, do not only check for the
1379 // correct trait, but also the correct type parameters.
1380 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1381 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1382 let upcast_trait_refs
=
1383 util
::supertraits(self.tcx(), poly_trait_ref
)
1384 .filter(|upcast_trait_ref
| {
1385 self.infcx
.probe(|_
| {
1386 let upcast_trait_ref
= upcast_trait_ref
.clone();
1387 self.match_poly_trait_ref(obligation
, upcast_trait_ref
).is_ok()
1392 if upcast_trait_refs
> 1 {
1393 // can be upcast in many ways; need more type information
1394 candidates
.ambiguous
= true;
1395 } else if upcast_trait_refs
== 1 {
1396 candidates
.vec
.push(ObjectCandidate
);
1403 /// Search for unsizing that might apply to `obligation`.
1404 fn assemble_candidates_for_unsizing(&mut self,
1405 obligation
: &TraitObligation
<'tcx
>,
1406 candidates
: &mut SelectionCandidateSet
<'tcx
>) {
1407 // We currently never consider higher-ranked obligations e.g.
1408 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1409 // because they are a priori invalid, and we could potentially add support
1410 // for them later, it's just that there isn't really a strong need for it.
1411 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1412 // impl, and those are generally applied to concrete types.
1414 // That said, one might try to write a fn with a where clause like
1415 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1416 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1417 // Still, you'd be more likely to write that where clause as
1419 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1420 // obligation above. Should be possible to extend this in the future.
1421 let source
= match self.tcx().no_late_bound_regions(&obligation
.self_ty()) {
1424 // Don't add any candidates if there are bound regions.
1428 let target
= obligation
.predicate
.0.input_types
()[0];
1430 debug
!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1433 let may_apply
= match (&source
.sty
, &target
.sty
) {
1434 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1435 (&ty
::TyTrait(ref data_a
), &ty
::TyTrait(ref data_b
)) => {
1436 // Upcasts permit two things:
1438 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1439 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1441 // Note that neither of these changes requires any
1442 // change at runtime. Eventually this will be
1445 // We always upcast when we can because of reason
1446 // #2 (region bounds).
1447 data_a
.principal
.def_id() == data_a
.principal
.def_id() &&
1448 data_a
.bounds
.builtin_bounds
.is_superset(&data_b
.bounds
.builtin_bounds
)
1452 (_
, &ty
::TyTrait(_
)) => true,
1454 // Ambiguous handling is below T -> Trait, because inference
1455 // variables can still implement Unsize<Trait> and nested
1456 // obligations will have the final say (likely deferred).
1457 (&ty
::TyInfer(ty
::TyVar(_
)), _
) |
1458 (_
, &ty
::TyInfer(ty
::TyVar(_
))) => {
1459 debug
!("assemble_candidates_for_unsizing: ambiguous");
1460 candidates
.ambiguous
= true;
1465 (&ty
::TyArray(_
, _
), &ty
::TySlice(_
)) => true,
1467 // Struct<T> -> Struct<U>.
1468 (&ty
::TyStruct(def_id_a
, _
), &ty
::TyStruct(def_id_b
, _
)) => {
1469 def_id_a
== def_id_b
1476 candidates
.vec
.push(BuiltinUnsizeCandidate
);
1480 ///////////////////////////////////////////////////////////////////////////
1483 // Winnowing is the process of attempting to resolve ambiguity by
1484 // probing further. During the winnowing process, we unify all
1485 // type variables (ignoring skolemization) and then we also
1486 // attempt to evaluate recursive bounds to see if they are
1489 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1490 /// obligations are met. Returns true if `candidate` remains viable after this further
1492 fn winnow_candidate
<'o
>(&mut self,
1493 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1494 candidate
: &SelectionCandidate
<'tcx
>)
1495 -> EvaluationResult
<'tcx
>
1497 debug
!("winnow_candidate: candidate={:?}", candidate
);
1498 let result
= self.infcx
.probe(|_
| {
1499 let candidate
= (*candidate
).clone();
1500 match self.confirm_candidate(stack
.obligation
, candidate
) {
1501 Ok(selection
) => self.winnow_selection(stack
.list(),
1503 Err(error
) => EvaluatedToErr(error
),
1506 debug
!("winnow_candidate depth={} result={:?}",
1507 stack
.obligation
.recursion_depth
, result
);
1511 fn winnow_selection
<'o
>(&mut self,
1512 stack
: TraitObligationStackList
<'o
,'tcx
>,
1513 selection
: Selection
<'tcx
>)
1514 -> EvaluationResult
<'tcx
>
1516 self.evaluate_predicates_recursively(stack
,
1517 selection
.nested_obligations().iter())
1520 /// Returns true if `candidate_i` should be dropped in favor of
1521 /// `candidate_j`. Generally speaking we will drop duplicate
1522 /// candidates and prefer where-clause candidates.
1523 /// Returns true if `victim` should be dropped in favor of
1524 /// `other`. Generally speaking we will drop duplicate
1525 /// candidates and prefer where-clause candidates.
1527 /// See the comment for "SelectionCandidate" for more details.
1528 fn candidate_should_be_dropped_in_favor_of
<'o
>(&mut self,
1529 victim
: &SelectionCandidate
<'tcx
>,
1530 other
: &SelectionCandidate
<'tcx
>)
1533 if victim
== other
{
1538 &ObjectCandidate(..) |
1539 &ParamCandidate(_
) | &ProjectionCandidate
=> match victim
{
1540 &DefaultImplCandidate(..) => {
1541 self.tcx().sess
.bug(
1542 "default implementations shouldn't be recorded \
1543 when there are other valid candidates");
1545 &PhantomFnCandidate
=> {
1546 self.tcx().sess
.bug("PhantomFn didn't short-circuit selection");
1548 &ImplCandidate(..) |
1549 &ClosureCandidate(..) |
1550 &FnPointerCandidate(..) |
1551 &BuiltinObjectCandidate(..) |
1552 &BuiltinUnsizeCandidate(..) |
1553 &DefaultImplObjectCandidate(..) |
1554 &BuiltinCandidate(..) => {
1555 // We have a where-clause so don't go around looking
1559 &ObjectCandidate(..) |
1560 &ProjectionCandidate
=> {
1561 // Arbitrarily give param candidates priority
1562 // over projection and object candidates.
1565 &ParamCandidate(..) => false,
1566 &ErrorCandidate
=> false // propagate errors
1572 ///////////////////////////////////////////////////////////////////////////
1575 // These cover the traits that are built-in to the language
1576 // itself. This includes `Copy` and `Sized` for sure. For the
1577 // moment, it also includes `Send` / `Sync` and a few others, but
1578 // those will hopefully change to library-defined traits in the
1581 fn assemble_builtin_bound_candidates
<'o
>(&mut self,
1582 bound
: ty
::BuiltinBound
,
1583 obligation
: &TraitObligation
<'tcx
>,
1584 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1585 -> Result
<(),SelectionError
<'tcx
>>
1587 match self.builtin_bound(bound
, obligation
) {
1589 debug
!("builtin_bound: bound={:?}",
1591 candidates
.vec
.push(BuiltinCandidate(bound
));
1594 Ok(ParameterBuiltin
) => { Ok(()) }
1595 Ok(AmbiguousBuiltin
) => {
1596 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1597 Ok(candidates
.ambiguous
= true)
1599 Err(e
) => { Err(e) }
1603 fn builtin_bound(&mut self,
1604 bound
: ty
::BuiltinBound
,
1605 obligation
: &TraitObligation
<'tcx
>)
1606 -> Result
<BuiltinBoundConditions
<'tcx
>,SelectionError
<'tcx
>>
1608 // Note: these tests operate on types that may contain bound
1609 // regions. To be proper, we ought to skolemize here, but we
1610 // forego the skolemization and defer it until the
1611 // confirmation step.
1613 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.0.self_ty());
1614 return match self_ty
.sty
{
1615 ty
::TyInfer(ty
::IntVar(_
)) |
1616 ty
::TyInfer(ty
::FloatVar(_
)) |
1623 // safe for everything
1627 ty
::TyBox(_
) => { // Box<T>
1629 ty
::BoundCopy
=> Err(Unimplemented
),
1631 ty
::BoundSized
=> ok_if(Vec
::new()),
1633 ty
::BoundSync
| ty
::BoundSend
=> {
1634 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1639 ty
::TyRawPtr(..) => { // *const T, *mut T
1641 ty
::BoundCopy
| ty
::BoundSized
=> ok_if(Vec
::new()),
1643 ty
::BoundSync
| ty
::BoundSend
=> {
1644 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1649 ty
::TyTrait(ref data
) => {
1651 ty
::BoundSized
=> Err(Unimplemented
),
1653 if data
.bounds
.builtin_bounds
.contains(&bound
) {
1656 // Recursively check all supertraits to find out if any further
1657 // bounds are required and thus we must fulfill.
1659 data
.principal_trait_ref_with_self_ty(self.tcx(),
1660 self.tcx().types
.err
);
1661 let copy_def_id
= obligation
.predicate
.def_id();
1662 for tr
in util
::supertraits(self.tcx(), principal
) {
1663 if tr
.def_id() == copy_def_id
{
1664 return ok_if(Vec
::new())
1671 ty
::BoundSync
| ty
::BoundSend
=> {
1672 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1677 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl }
) => {
1682 // &mut T is affine and hence never `Copy`
1683 hir
::MutMutable
=> Err(Unimplemented
),
1685 // &T is always copyable
1686 hir
::MutImmutable
=> ok_if(Vec
::new()),
1690 ty
::BoundSized
=> ok_if(Vec
::new()),
1692 ty
::BoundSync
| ty
::BoundSend
=> {
1693 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1698 ty
::TyArray(element_ty
, _
) => {
1701 ty
::BoundCopy
=> ok_if(vec
![element_ty
]),
1702 ty
::BoundSized
=> ok_if(Vec
::new()),
1703 ty
::BoundSync
| ty
::BoundSend
=> {
1704 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1709 ty
::TyStr
| ty
::TySlice(_
) => {
1711 ty
::BoundSync
| ty
::BoundSend
=> {
1712 self.tcx().sess
.bug("Send/Sync shouldn't occur in builtin_bounds()");
1715 ty
::BoundCopy
| ty
::BoundSized
=> Err(Unimplemented
),
1719 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1720 ty
::TyTuple(ref tys
) => ok_if(tys
.clone()),
1722 ty
::TyClosure(def_id
, ref substs
) => {
1723 // FIXME -- This case is tricky. In the case of by-ref
1724 // closures particularly, we need the results of
1725 // inference to decide how to reflect the type of each
1726 // upvar (the upvar may have type `T`, but the runtime
1727 // type could be `&mut`, `&`, or just `T`). For now,
1728 // though, we'll do this unsoundly and assume that all
1729 // captures are by value. Really what we ought to do
1730 // is reserve judgement and then intertwine this
1731 // analysis with closure inference.
1732 assert_eq
!(def_id
.krate
, LOCAL_CRATE
);
1734 // Unboxed closures shouldn't be
1735 // implicitly copyable
1736 if bound
== ty
::BoundCopy
{
1737 return Ok(ParameterBuiltin
);
1740 // Upvars are always local variables or references to
1741 // local variables, and local variables cannot be
1742 // unsized, so the closure struct as a whole must be
1744 if bound
== ty
::BoundSized
{
1745 return ok_if(Vec
::new());
1748 ok_if(substs
.upvar_tys
.clone())
1751 ty
::TyStruct(def
, substs
) | ty
::TyEnum(def
, substs
) => {
1752 let types
: Vec
<Ty
> = def
.all_fields().map(|f
| {
1753 f
.ty(self.tcx(), substs
)
1755 nominal(bound
, types
)
1758 ty
::TyProjection(_
) | ty
::TyParam(_
) => {
1759 // Note: A type parameter is only considered to meet a
1760 // particular bound if there is a where clause telling
1761 // us that it does, and that case is handled by
1762 // `assemble_candidates_from_caller_bounds()`.
1763 Ok(ParameterBuiltin
)
1766 ty
::TyInfer(ty
::TyVar(_
)) => {
1767 // Unbound type variable. Might or might not have
1768 // applicable impls and so forth, depending on what
1769 // those type variables wind up being bound to.
1770 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1771 Ok(AmbiguousBuiltin
)
1774 ty
::TyError
=> ok_if(Vec
::new()),
1776 ty
::TyInfer(ty
::FreshTy(_
))
1777 | ty
::TyInfer(ty
::FreshIntTy(_
))
1778 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1779 self.tcx().sess
.bug(
1781 "asked to assemble builtin bounds of unexpected type: {:?}",
1786 fn ok_if
<'tcx
>(v
: Vec
<Ty
<'tcx
>>)
1787 -> Result
<BuiltinBoundConditions
<'tcx
>, SelectionError
<'tcx
>> {
1788 Ok(If(ty
::Binder(v
)))
1791 fn nominal
<'cx
, 'tcx
>(bound
: ty
::BuiltinBound
,
1792 types
: Vec
<Ty
<'tcx
>>)
1793 -> Result
<BuiltinBoundConditions
<'tcx
>, SelectionError
<'tcx
>>
1795 // First check for markers and other nonsense.
1797 // Fallback to whatever user-defined impls exist in this case.
1798 ty
::BoundCopy
=> Ok(ParameterBuiltin
),
1800 // Sized if all the component types are sized.
1801 ty
::BoundSized
=> ok_if(types
),
1803 // Shouldn't be coming through here.
1804 ty
::BoundSend
| ty
::BoundSync
=> unreachable
!(),
1809 /// For default impls, we need to break apart a type into its
1810 /// "constituent types" -- meaning, the types that it contains.
1812 /// Here are some (simple) examples:
1815 /// (i32, u32) -> [i32, u32]
1816 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1817 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1818 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1820 fn constituent_types_for_ty(&self, t
: Ty
<'tcx
>) -> Vec
<Ty
<'tcx
>> {
1829 ty
::TyInfer(ty
::IntVar(_
)) |
1830 ty
::TyInfer(ty
::FloatVar(_
)) |
1837 ty
::TyProjection(..) |
1838 ty
::TyInfer(ty
::TyVar(_
)) |
1839 ty
::TyInfer(ty
::FreshTy(_
)) |
1840 ty
::TyInfer(ty
::FreshIntTy(_
)) |
1841 ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1842 self.tcx().sess
.bug(
1844 "asked to assemble constituent types of unexpected type: {:?}",
1848 ty
::TyBox(referent_ty
) => { // Box<T>
1852 ty
::TyRawPtr(ty
::TypeAndMut { ty: element_ty, ..}
) |
1853 ty
::TyRef(_
, ty
::TypeAndMut { ty: element_ty, ..}
) => {
1857 ty
::TyArray(element_ty
, _
) | ty
::TySlice(element_ty
) => {
1861 ty
::TyTuple(ref tys
) => {
1862 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1866 ty
::TyClosure(def_id
, ref substs
) => {
1867 // FIXME(#27086). We are invariant w/r/t our
1868 // substs.func_substs, but we don't see them as
1869 // constituent types; this seems RIGHT but also like
1870 // something that a normal type couldn't simulate. Is
1871 // this just a gap with the way that PhantomData and
1872 // OIBIT interact? That is, there is no way to say
1873 // "make me invariant with respect to this TYPE, but
1874 // do not act as though I can reach it"
1875 assert_eq
!(def_id
.krate
, LOCAL_CRATE
);
1876 substs
.upvar_tys
.clone()
1879 // for `PhantomData<T>`, we pass `T`
1880 ty
::TyStruct(def
, substs
) if def
.is_phantom_data() => {
1881 substs
.types
.get_slice(TypeSpace
).to_vec()
1884 ty
::TyStruct(def
, substs
) | ty
::TyEnum(def
, substs
) => {
1886 .map(|f
| f
.ty(self.tcx(), substs
))
1892 fn collect_predicates_for_types(&mut self,
1893 obligation
: &TraitObligation
<'tcx
>,
1894 trait_def_id
: DefId
,
1895 types
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
1896 -> Vec
<PredicateObligation
<'tcx
>>
1898 let derived_cause
= match self.tcx().lang_items
.to_builtin_kind(trait_def_id
) {
1900 self.derived_cause(obligation
, BuiltinDerivedObligation
)
1903 self.derived_cause(obligation
, ImplDerivedObligation
)
1907 // Because the types were potentially derived from
1908 // higher-ranked obligations they may reference late-bound
1909 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1910 // yield a type like `for<'a> &'a int`. In general, we
1911 // maintain the invariant that we never manipulate bound
1912 // regions, so we have to process these bound regions somehow.
1914 // The strategy is to:
1916 // 1. Instantiate those regions to skolemized regions (e.g.,
1917 // `for<'a> &'a int` becomes `&0 int`.
1918 // 2. Produce something like `&'0 int : Copy`
1919 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1921 // Move the binder into the individual types
1922 let bound_types
: Vec
<ty
::Binder
<Ty
<'tcx
>>> =
1925 .map(|&nested_ty
| ty
::Binder(nested_ty
))
1928 // For each type, produce a vector of resulting obligations
1929 let obligations
: Result
<Vec
<Vec
<_
>>, _
> = bound_types
.iter().map(|nested_ty
| {
1930 self.infcx
.commit_if_ok(|snapshot
| {
1931 let (skol_ty
, skol_map
) =
1932 self.infcx().skolemize_late_bound_regions(nested_ty
, snapshot
);
1933 let Normalized { value: normalized_ty, mut obligations }
=
1934 project
::normalize_with_depth(self,
1935 obligation
.cause
.clone(),
1936 obligation
.recursion_depth
+ 1,
1938 let skol_obligation
=
1939 util
::predicate_for_trait_def(self.tcx(),
1940 derived_cause
.clone(),
1942 obligation
.recursion_depth
+ 1,
1945 obligations
.push(skol_obligation
);
1946 Ok(self.infcx().plug_leaks(skol_map
, snapshot
, &obligations
))
1950 // Flatten those vectors (couldn't do it above due `collect`)
1952 Ok(obligations
) => obligations
.into_iter().flat_map(|o
| o
).collect(),
1953 Err(ErrorReported
) => Vec
::new(),
1957 ///////////////////////////////////////////////////////////////////////////
1960 // Confirmation unifies the output type parameters of the trait
1961 // with the values found in the obligation, possibly yielding a
1962 // type error. See `README.md` for more details.
1964 fn confirm_candidate(&mut self,
1965 obligation
: &TraitObligation
<'tcx
>,
1966 candidate
: SelectionCandidate
<'tcx
>)
1967 -> Result
<Selection
<'tcx
>,SelectionError
<'tcx
>>
1969 debug
!("confirm_candidate({:?}, {:?})",
1974 BuiltinCandidate(builtin_bound
) => {
1976 try
!(self.confirm_builtin_candidate(obligation
, builtin_bound
))))
1979 PhantomFnCandidate
|
1981 Ok(VtableBuiltin(VtableBuiltinData { nested: vec![] }
))
1984 ParamCandidate(param
) => {
1985 let obligations
= self.confirm_param_candidate(obligation
, param
);
1986 Ok(VtableParam(obligations
))
1989 DefaultImplCandidate(trait_def_id
) => {
1990 let data
= self.confirm_default_impl_candidate(obligation
, trait_def_id
);
1991 Ok(VtableDefaultImpl(data
))
1994 DefaultImplObjectCandidate(trait_def_id
) => {
1995 let data
= self.confirm_default_impl_object_candidate(obligation
, trait_def_id
);
1996 Ok(VtableDefaultImpl(data
))
1999 ImplCandidate(impl_def_id
) => {
2001 try
!(self.confirm_impl_candidate(obligation
, impl_def_id
));
2002 Ok(VtableImpl(vtable_impl
))
2005 ClosureCandidate(closure_def_id
, substs
) => {
2006 let vtable_closure
=
2007 try
!(self.confirm_closure_candidate(obligation
, closure_def_id
, substs
));
2008 Ok(VtableClosure(vtable_closure
))
2011 BuiltinObjectCandidate
=> {
2012 // This indicates something like `(Trait+Send) :
2013 // Send`. In this case, we know that this holds
2014 // because that's what the object type is telling us,
2015 // and there's really no additional obligations to
2016 // prove and no types in particular to unify etc.
2017 Ok(VtableParam(Vec
::new()))
2020 ObjectCandidate
=> {
2021 let data
= self.confirm_object_candidate(obligation
);
2022 Ok(VtableObject(data
))
2025 FnPointerCandidate
=> {
2027 try
!(self.confirm_fn_pointer_candidate(obligation
));
2028 Ok(VtableFnPointer(fn_type
))
2031 ProjectionCandidate
=> {
2032 self.confirm_projection_candidate(obligation
);
2033 Ok(VtableParam(Vec
::new()))
2036 BuiltinUnsizeCandidate
=> {
2037 let data
= try
!(self.confirm_builtin_unsize_candidate(obligation
));
2038 Ok(VtableBuiltin(data
))
2043 fn confirm_projection_candidate(&mut self,
2044 obligation
: &TraitObligation
<'tcx
>)
2046 let _
: Result
<(),()> =
2047 self.infcx
.commit_if_ok(|snapshot
| {
2049 self.match_projection_obligation_against_bounds_from_trait(obligation
,
2056 fn confirm_param_candidate(&mut self,
2057 obligation
: &TraitObligation
<'tcx
>,
2058 param
: ty
::PolyTraitRef
<'tcx
>)
2059 -> Vec
<PredicateObligation
<'tcx
>>
2061 debug
!("confirm_param_candidate({:?},{:?})",
2065 // During evaluation, we already checked that this
2066 // where-clause trait-ref could be unified with the obligation
2067 // trait-ref. Repeat that unification now without any
2068 // transactional boundary; it should not fail.
2069 match self.match_where_clause_trait_ref(obligation
, param
.clone()) {
2070 Ok(obligations
) => obligations
,
2072 self.tcx().sess
.bug(
2073 &format
!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2080 fn confirm_builtin_candidate(&mut self,
2081 obligation
: &TraitObligation
<'tcx
>,
2082 bound
: ty
::BuiltinBound
)
2083 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2084 SelectionError
<'tcx
>>
2086 debug
!("confirm_builtin_candidate({:?})",
2089 match try
!(self.builtin_bound(bound
, obligation
)) {
2090 If(nested
) => Ok(self.vtable_builtin_data(obligation
, bound
, nested
)),
2091 AmbiguousBuiltin
| ParameterBuiltin
=> {
2092 self.tcx().sess
.span_bug(
2093 obligation
.cause
.span
,
2094 &format
!("builtin bound for {:?} was ambig",
2100 fn vtable_builtin_data(&mut self,
2101 obligation
: &TraitObligation
<'tcx
>,
2102 bound
: ty
::BuiltinBound
,
2103 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2104 -> VtableBuiltinData
<PredicateObligation
<'tcx
>>
2106 let trait_def
= match self.tcx().lang_items
.from_builtin_kind(bound
) {
2107 Ok(def_id
) => def_id
,
2109 self.tcx().sess
.bug("builtin trait definition not found");
2113 let obligations
= self.collect_predicates_for_types(obligation
, trait_def
, nested
);
2115 debug
!("vtable_builtin_data: obligations={:?}",
2118 VtableBuiltinData { nested: obligations }
2121 /// This handles the case where a `impl Foo for ..` impl is being used.
2122 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2124 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2125 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2126 fn confirm_default_impl_candidate(&mut self,
2127 obligation
: &TraitObligation
<'tcx
>,
2128 trait_def_id
: DefId
)
2129 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2131 debug
!("confirm_default_impl_candidate({:?}, {:?})",
2135 // binder is moved below
2136 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2137 let types
= self.constituent_types_for_ty(self_ty
);
2138 self.vtable_default_impl(obligation
, trait_def_id
, ty
::Binder(types
))
2141 fn confirm_default_impl_object_candidate(&mut self,
2142 obligation
: &TraitObligation
<'tcx
>,
2143 trait_def_id
: DefId
)
2144 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2146 debug
!("confirm_default_impl_object_candidate({:?}, {:?})",
2150 assert
!(self.tcx().has_attr(trait_def_id
, "rustc_reflect_like"));
2152 // OK to skip binder, it is reintroduced below
2153 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2155 ty
::TyTrait(ref data
) => {
2156 // OK to skip the binder, it is reintroduced below
2157 let input_types
= data
.principal
.skip_binder().substs
.types
.get_slice(TypeSpace
);
2158 let assoc_types
= data
.bounds
.projection_bounds
2160 .map(|pb
| pb
.skip_binder().ty
);
2161 let all_types
: Vec
<_
> = input_types
.iter().cloned()
2165 // reintroduce the two binding levels we skipped, then flatten into one
2166 let all_types
= ty
::Binder(ty
::Binder(all_types
));
2167 let all_types
= self.tcx().flatten_late_bound_regions(&all_types
);
2169 self.vtable_default_impl(obligation
, trait_def_id
, all_types
)
2172 self.tcx().sess
.bug(
2174 "asked to confirm default object implementation for non-object type: {:?}",
2180 /// See `confirm_default_impl_candidate`
2181 fn vtable_default_impl(&mut self,
2182 obligation
: &TraitObligation
<'tcx
>,
2183 trait_def_id
: DefId
,
2184 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2185 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2187 debug
!("vtable_default_impl_data: nested={:?}", nested
);
2189 let mut obligations
= self.collect_predicates_for_types(obligation
,
2193 let trait_obligations
: Result
<Vec
<_
>,()> = self.infcx
.commit_if_ok(|snapshot
| {
2194 let poly_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
2195 let (trait_ref
, skol_map
) =
2196 self.infcx().skolemize_late_bound_regions(&poly_trait_ref
, snapshot
);
2197 Ok(self.impl_or_trait_obligations(obligation
.cause
.clone(),
2198 obligation
.recursion_depth
+ 1,
2205 // no Errors in that code above
2206 obligations
.append(&mut trait_obligations
.unwrap());
2208 debug
!("vtable_default_impl_data: obligations={:?}", obligations
);
2210 VtableDefaultImplData
{
2211 trait_def_id
: trait_def_id
,
2216 fn confirm_impl_candidate(&mut self,
2217 obligation
: &TraitObligation
<'tcx
>,
2219 -> Result
<VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>,
2220 SelectionError
<'tcx
>>
2222 debug
!("confirm_impl_candidate({:?},{:?})",
2226 // First, create the substitutions by matching the impl again,
2227 // this time not in a probe.
2228 self.infcx
.commit_if_ok(|snapshot
| {
2229 let (substs
, skol_map
) =
2230 self.rematch_impl(impl_def_id
, obligation
,
2232 debug
!("confirm_impl_candidate substs={:?}", substs
);
2233 Ok(self.vtable_impl(impl_def_id
, substs
, obligation
.cause
.clone(),
2234 obligation
.recursion_depth
+ 1, skol_map
, snapshot
))
2238 fn vtable_impl(&mut self,
2240 mut substs
: Normalized
<'tcx
, Substs
<'tcx
>>,
2241 cause
: ObligationCause
<'tcx
>,
2242 recursion_depth
: usize,
2243 skol_map
: infer
::SkolemizationMap
,
2244 snapshot
: &infer
::CombinedSnapshot
)
2245 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2247 debug
!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2253 let mut impl_obligations
=
2254 self.impl_or_trait_obligations(cause
,
2261 debug
!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2265 impl_obligations
.append(&mut substs
.obligations
);
2267 VtableImplData
{ impl_def_id
: impl_def_id
,
2268 substs
: substs
.value
,
2269 nested
: impl_obligations
}
2272 fn confirm_object_candidate(&mut self,
2273 obligation
: &TraitObligation
<'tcx
>)
2274 -> VtableObjectData
<'tcx
>
2276 debug
!("confirm_object_candidate({:?})",
2279 // FIXME skipping binder here seems wrong -- we should
2280 // probably flatten the binder from the obligation and the
2281 // binder from the object. Have to try to make a broken test
2282 // case that results. -nmatsakis
2283 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2284 let poly_trait_ref
= match self_ty
.sty
{
2285 ty
::TyTrait(ref data
) => {
2286 data
.principal_trait_ref_with_self_ty(self.tcx(), self_ty
)
2289 self.tcx().sess
.span_bug(obligation
.cause
.span
,
2290 "object candidate with non-object");
2294 let mut upcast_trait_ref
= None
;
2298 // We want to find the first supertrait in the list of
2299 // supertraits that we can unify with, and do that
2300 // unification. We know that there is exactly one in the list
2301 // where we can unify because otherwise select would have
2302 // reported an ambiguity. (When we do find a match, also
2303 // record it for later.)
2305 util
::supertraits(self.tcx(), poly_trait_ref
)
2308 self.infcx
.commit_if_ok(
2309 |_
| self.match_poly_trait_ref(obligation
, t
))
2311 Ok(_
) => { upcast_trait_ref = Some(t); false }
2316 // Additionally, for each of the nonmatching predicates that
2317 // we pass over, we sum up the set of number of vtable
2318 // entries, so that we can compute the offset for the selected
2321 nonmatching
.map(|t
| util
::count_own_vtable_entries(self.tcx(), t
))
2327 upcast_trait_ref
: upcast_trait_ref
.unwrap(),
2328 vtable_base
: vtable_base
,
2332 fn confirm_fn_pointer_candidate(&mut self,
2333 obligation
: &TraitObligation
<'tcx
>)
2334 -> Result
<ty
::Ty
<'tcx
>,SelectionError
<'tcx
>>
2336 debug
!("confirm_fn_pointer_candidate({:?})",
2339 // ok to skip binder; it is reintroduced below
2340 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2341 let sig
= self_ty
.fn_sig();
2343 util
::closure_trait_ref_and_return_type(self.tcx(),
2344 obligation
.predicate
.def_id(),
2347 util
::TupleArgumentsFlag
::Yes
)
2348 .map_bound(|(trait_ref
, _
)| trait_ref
);
2350 try
!(self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2351 obligation
.predicate
.to_poly_trait_ref(),
2356 fn confirm_closure_candidate(&mut self,
2357 obligation
: &TraitObligation
<'tcx
>,
2358 closure_def_id
: DefId
,
2359 substs
: &ty
::ClosureSubsts
<'tcx
>)
2360 -> Result
<VtableClosureData
<'tcx
, PredicateObligation
<'tcx
>>,
2361 SelectionError
<'tcx
>>
2363 debug
!("confirm_closure_candidate({:?},{:?},{:?})",
2371 } = self.closure_trait_ref(obligation
, closure_def_id
, substs
);
2373 debug
!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2378 try
!(self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2379 obligation
.predicate
.to_poly_trait_ref(),
2382 Ok(VtableClosureData
{
2383 closure_def_id
: closure_def_id
,
2384 substs
: substs
.clone(),
2389 /// In the case of closure types and fn pointers,
2390 /// we currently treat the input type parameters on the trait as
2391 /// outputs. This means that when we have a match we have only
2392 /// considered the self type, so we have to go back and make sure
2393 /// to relate the argument types too. This is kind of wrong, but
2394 /// since we control the full set of impls, also not that wrong,
2395 /// and it DOES yield better error messages (since we don't report
2396 /// errors as if there is no applicable impl, but rather report
2397 /// errors are about mismatched argument types.
2399 /// Here is an example. Imagine we have an closure expression
2400 /// and we desugared it so that the type of the expression is
2401 /// `Closure`, and `Closure` expects an int as argument. Then it
2402 /// is "as if" the compiler generated this impl:
2404 /// impl Fn(int) for Closure { ... }
2406 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2407 /// we have matched the self-type `Closure`. At this point we'll
2408 /// compare the `int` to `usize` and generate an error.
2410 /// Note that this checking occurs *after* the impl has selected,
2411 /// because these output type parameters should not affect the
2412 /// selection of the impl. Therefore, if there is a mismatch, we
2413 /// report an error to the user.
2414 fn confirm_poly_trait_refs(&mut self,
2415 obligation_cause
: ObligationCause
,
2416 obligation_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2417 expected_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2418 -> Result
<(), SelectionError
<'tcx
>>
2420 let origin
= infer
::RelateOutputImplTypes(obligation_cause
.span
);
2422 let obligation_trait_ref
= obligation_trait_ref
.clone();
2423 match self.infcx
.sub_poly_trait_refs(false,
2425 expected_trait_ref
.clone(),
2426 obligation_trait_ref
.clone()) {
2428 Err(e
) => Err(OutputTypeParameterMismatch(expected_trait_ref
, obligation_trait_ref
, e
))
2432 fn confirm_builtin_unsize_candidate(&mut self,
2433 obligation
: &TraitObligation
<'tcx
>,)
2434 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2435 SelectionError
<'tcx
>> {
2436 let tcx
= self.tcx();
2438 // assemble_candidates_for_unsizing should ensure there are no late bound
2439 // regions here. See the comment there for more details.
2440 let source
= self.infcx
.shallow_resolve(
2441 tcx
.no_late_bound_regions(&obligation
.self_ty()).unwrap());
2442 let target
= self.infcx
.shallow_resolve(obligation
.predicate
.0.input_types
()[0]);
2444 debug
!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2447 let mut nested
= vec
![];
2448 match (&source
.sty
, &target
.sty
) {
2449 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2450 (&ty
::TyTrait(ref data_a
), &ty
::TyTrait(ref data_b
)) => {
2451 // See assemble_candidates_for_unsizing for more info.
2452 let bounds
= ty
::ExistentialBounds
{
2453 region_bound
: data_b
.bounds
.region_bound
,
2454 builtin_bounds
: data_b
.bounds
.builtin_bounds
,
2455 projection_bounds
: data_a
.bounds
.projection_bounds
.clone(),
2458 let new_trait
= tcx
.mk_trait(data_a
.principal
.clone(), bounds
);
2459 let origin
= infer
::Misc(obligation
.cause
.span
);
2460 if self.infcx
.sub_types(false, origin
, new_trait
, target
).is_err() {
2461 return Err(Unimplemented
);
2464 // Register one obligation for 'a: 'b.
2465 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2466 obligation
.cause
.body_id
,
2467 ObjectCastObligation(target
));
2468 let outlives
= ty
::OutlivesPredicate(data_a
.bounds
.region_bound
,
2469 data_b
.bounds
.region_bound
);
2470 nested
.push(Obligation
::with_depth(cause
,
2471 obligation
.recursion_depth
+ 1,
2472 ty
::Binder(outlives
).to_predicate()));
2476 (_
, &ty
::TyTrait(ref data
)) => {
2477 let object_did
= data
.principal_def_id();
2478 if !object_safety
::is_object_safe(tcx
, object_did
) {
2479 return Err(TraitNotObjectSafe(object_did
));
2482 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2483 obligation
.cause
.body_id
,
2484 ObjectCastObligation(target
));
2485 let mut push
= |predicate
| {
2486 nested
.push(Obligation
::with_depth(cause
.clone(),
2487 obligation
.recursion_depth
+ 1,
2491 // Create the obligation for casting from T to Trait.
2492 push(data
.principal_trait_ref_with_self_ty(tcx
, source
).to_predicate());
2494 // We can only make objects from sized types.
2495 let mut builtin_bounds
= data
.bounds
.builtin_bounds
;
2496 builtin_bounds
.insert(ty
::BoundSized
);
2498 // Create additional obligations for all the various builtin
2499 // bounds attached to the object cast. (In other words, if the
2500 // object type is Foo+Send, this would create an obligation
2501 // for the Send check.)
2502 for bound
in &builtin_bounds
{
2503 if let Ok(tr
) = util
::trait_ref_for_builtin_bound(tcx
, bound
, source
) {
2504 push(tr
.to_predicate());
2506 return Err(Unimplemented
);
2510 // Create obligations for the projection predicates.
2511 for bound
in data
.projection_bounds_with_self_ty(tcx
, source
) {
2512 push(bound
.to_predicate());
2515 // If the type is `Foo+'a`, ensures that the type
2516 // being cast to `Foo+'a` outlives `'a`:
2517 let outlives
= ty
::OutlivesPredicate(source
,
2518 data
.bounds
.region_bound
);
2519 push(ty
::Binder(outlives
).to_predicate());
2523 (&ty
::TyArray(a
, _
), &ty
::TySlice(b
)) => {
2524 let origin
= infer
::Misc(obligation
.cause
.span
);
2525 if self.infcx
.sub_types(false, origin
, a
, b
).is_err() {
2526 return Err(Unimplemented
);
2530 // Struct<T> -> Struct<U>.
2531 (&ty
::TyStruct(def
, substs_a
), &ty
::TyStruct(_
, substs_b
)) => {
2534 .map(|f
| f
.unsubst_ty())
2535 .collect
::<Vec
<_
>>();
2537 // The last field of the structure has to exist and contain type parameters.
2538 let field
= if let Some(&field
) = fields
.last() {
2541 return Err(Unimplemented
);
2543 let mut ty_params
= vec
![];
2544 for ty
in field
.walk() {
2545 if let ty
::TyParam(p
) = ty
.sty
{
2546 assert
!(p
.space
== TypeSpace
);
2547 let idx
= p
.idx
as usize;
2548 if !ty_params
.contains(&idx
) {
2549 ty_params
.push(idx
);
2553 if ty_params
.is_empty() {
2554 return Err(Unimplemented
);
2557 // Replace type parameters used in unsizing with
2558 // TyError and ensure they do not affect any other fields.
2559 // This could be checked after type collection for any struct
2560 // with a potentially unsized trailing field.
2561 let mut new_substs
= substs_a
.clone();
2562 for &i
in &ty_params
{
2563 new_substs
.types
.get_mut_slice(TypeSpace
)[i
] = tcx
.types
.err
;
2565 for &ty
in fields
.split_last().unwrap().1 {
2566 if ty
.subst(tcx
, &new_substs
).references_error() {
2567 return Err(Unimplemented
);
2571 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2572 let inner_source
= field
.subst(tcx
, substs_a
);
2573 let inner_target
= field
.subst(tcx
, substs_b
);
2575 // Check that the source structure with the target's
2576 // type parameters is a subtype of the target.
2577 for &i
in &ty_params
{
2578 let param_b
= *substs_b
.types
.get(TypeSpace
, i
);
2579 new_substs
.types
.get_mut_slice(TypeSpace
)[i
] = param_b
;
2581 let new_struct
= tcx
.mk_struct(def
, tcx
.mk_substs(new_substs
));
2582 let origin
= infer
::Misc(obligation
.cause
.span
);
2583 if self.infcx
.sub_types(false, origin
, new_struct
, target
).is_err() {
2584 return Err(Unimplemented
);
2587 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2588 nested
.push(util
::predicate_for_trait_def(tcx
,
2589 obligation
.cause
.clone(),
2590 obligation
.predicate
.def_id(),
2591 obligation
.recursion_depth
+ 1,
2593 vec
![inner_target
]));
2599 Ok(VtableBuiltinData { nested: nested }
)
2602 ///////////////////////////////////////////////////////////////////////////
2605 // Matching is a common path used for both evaluation and
2606 // confirmation. It basically unifies types that appear in impls
2607 // and traits. This does affect the surrounding environment;
2608 // therefore, when used during evaluation, match routines must be
2609 // run inside of a `probe()` so that their side-effects are
2612 fn rematch_impl(&mut self,
2614 obligation
: &TraitObligation
<'tcx
>,
2615 snapshot
: &infer
::CombinedSnapshot
)
2616 -> (Normalized
<'tcx
, Substs
<'tcx
>>, infer
::SkolemizationMap
)
2618 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
2619 Ok((substs
, skol_map
)) => (substs
, skol_map
),
2621 self.tcx().sess
.bug(
2622 &format
!("Impl {:?} was matchable against {:?} but now is not",
2629 fn match_impl(&mut self,
2631 obligation
: &TraitObligation
<'tcx
>,
2632 snapshot
: &infer
::CombinedSnapshot
)
2633 -> Result
<(Normalized
<'tcx
, Substs
<'tcx
>>,
2634 infer
::SkolemizationMap
), ()>
2636 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2638 // Before we create the substitutions and everything, first
2639 // consider a "quick reject". This avoids creating more types
2640 // and so forth that we need to.
2641 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2645 let (skol_obligation
, skol_map
) = self.infcx().skolemize_late_bound_regions(
2646 &obligation
.predicate
,
2648 let skol_obligation_trait_ref
= skol_obligation
.trait_ref
;
2650 let impl_substs
= util
::fresh_type_vars_for_impl(self.infcx
,
2651 obligation
.cause
.span
,
2654 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(),
2657 let impl_trait_ref
=
2658 project
::normalize_with_depth(self,
2659 obligation
.cause
.clone(),
2660 obligation
.recursion_depth
+ 1,
2663 debug
!("match_impl(impl_def_id={:?}, obligation={:?}, \
2664 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2668 skol_obligation_trait_ref
);
2670 let origin
= infer
::RelateOutputImplTypes(obligation
.cause
.span
);
2671 if let Err(e
) = self.infcx
.sub_trait_refs(false,
2673 impl_trait_ref
.value
.clone(),
2674 skol_obligation_trait_ref
) {
2675 debug
!("match_impl: failed sub_trait_refs due to `{}`", e
);
2679 if let Err(e
) = self.infcx
.leak_check(&skol_map
, snapshot
) {
2680 debug
!("match_impl: failed leak check due to `{}`", e
);
2684 debug
!("match_impl: success impl_substs={:?}", impl_substs
);
2687 obligations
: impl_trait_ref
.obligations
2691 fn fast_reject_trait_refs(&mut self,
2692 obligation
: &TraitObligation
,
2693 impl_trait_ref
: &ty
::TraitRef
)
2696 // We can avoid creating type variables and doing the full
2697 // substitution if we find that any of the input types, when
2698 // simplified, do not match.
2700 obligation
.predicate
.0.input_types
().iter()
2701 .zip(impl_trait_ref
.input_types())
2702 .any(|(&obligation_ty
, &impl_ty
)| {
2703 let simplified_obligation_ty
=
2704 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2705 let simplified_impl_ty
=
2706 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2708 simplified_obligation_ty
.is_some() &&
2709 simplified_impl_ty
.is_some() &&
2710 simplified_obligation_ty
!= simplified_impl_ty
2714 /// Normalize `where_clause_trait_ref` and try to match it against
2715 /// `obligation`. If successful, return any predicates that
2716 /// result from the normalization. Normalization is necessary
2717 /// because where-clauses are stored in the parameter environment
2719 fn match_where_clause_trait_ref(&mut self,
2720 obligation
: &TraitObligation
<'tcx
>,
2721 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2722 -> Result
<Vec
<PredicateObligation
<'tcx
>>,()>
2724 try
!(self.match_poly_trait_ref(obligation
, where_clause_trait_ref
));
2728 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2729 /// obligation is satisfied.
2730 fn match_poly_trait_ref(&self,
2731 obligation
: &TraitObligation
<'tcx
>,
2732 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2735 debug
!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2739 let origin
= infer
::RelateOutputImplTypes(obligation
.cause
.span
);
2740 match self.infcx
.sub_poly_trait_refs(false,
2743 obligation
.predicate
.to_poly_trait_ref()) {
2749 /// Determines whether the self type declared against
2750 /// `impl_def_id` matches `obligation_self_ty`. If successful,
2751 /// returns the substitutions used to make them match. See
2752 /// `match_impl()`. For example, if `impl_def_id` is declared
2755 /// impl<T:Copy> Foo for Box<T> { ... }
2757 /// and `obligation_self_ty` is `int`, we'd get back an `Err(_)`
2758 /// result. But if `obligation_self_ty` were `Box<int>`, we'd get
2759 /// back `Ok(T=int)`.
2760 fn match_inherent_impl(&mut self,
2762 obligation_cause
: &ObligationCause
,
2763 obligation_self_ty
: Ty
<'tcx
>)
2764 -> Result
<Substs
<'tcx
>,()>
2766 // Create fresh type variables for each type parameter declared
2768 let impl_substs
= util
::fresh_type_vars_for_impl(self.infcx
,
2769 obligation_cause
.span
,
2772 // Find the self type for the impl.
2773 let impl_self_ty
= self.tcx().lookup_item_type(impl_def_id
).ty
;
2774 let impl_self_ty
= impl_self_ty
.subst(self.tcx(), &impl_substs
);
2776 debug
!("match_impl_self_types(obligation_self_ty={:?}, impl_self_ty={:?})",
2780 match self.match_self_types(obligation_cause
,
2782 obligation_self_ty
) {
2784 debug
!("Matched impl_substs={:?}", impl_substs
);
2794 fn match_self_types(&mut self,
2795 cause
: &ObligationCause
,
2797 // The self type provided by the impl/caller-obligation:
2798 provided_self_ty
: Ty
<'tcx
>,
2800 // The self type the obligation is for:
2801 required_self_ty
: Ty
<'tcx
>)
2804 // FIXME(#5781) -- equating the types is stronger than
2805 // necessary. Should consider variance of trait w/r/t Self.
2807 let origin
= infer
::RelateSelfType(cause
.span
);
2808 match self.infcx
.eq_types(false,
2817 ///////////////////////////////////////////////////////////////////////////
2820 fn match_fresh_trait_refs(&self,
2821 previous
: &ty
::PolyTraitRef
<'tcx
>,
2822 current
: &ty
::PolyTraitRef
<'tcx
>)
2825 let mut matcher
= ty
::_match
::Match
::new(self.tcx());
2826 matcher
.relate(previous
, current
).is_ok()
2829 fn push_stack
<'o
,'s
:'o
>(&mut self,
2830 previous_stack
: TraitObligationStackList
<'s
, 'tcx
>,
2831 obligation
: &'o TraitObligation
<'tcx
>)
2832 -> TraitObligationStack
<'o
, 'tcx
>
2834 let fresh_trait_ref
=
2835 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2837 TraitObligationStack
{
2838 obligation
: obligation
,
2839 fresh_trait_ref
: fresh_trait_ref
,
2840 previous
: previous_stack
,
2844 fn closure_trait_ref_unnormalized(&mut self,
2845 obligation
: &TraitObligation
<'tcx
>,
2846 closure_def_id
: DefId
,
2847 substs
: &ty
::ClosureSubsts
<'tcx
>)
2848 -> ty
::PolyTraitRef
<'tcx
>
2850 let closure_type
= self.infcx
.closure_type(closure_def_id
, substs
);
2851 let ty
::Binder((trait_ref
, _
)) =
2852 util
::closure_trait_ref_and_return_type(self.tcx(),
2853 obligation
.predicate
.def_id(),
2854 obligation
.predicate
.0.self_ty(), // (1)
2856 util
::TupleArgumentsFlag
::No
);
2857 // (1) Feels icky to skip the binder here, but OTOH we know
2858 // that the self-type is an unboxed closure type and hence is
2859 // in fact unparameterized (or at least does not reference any
2860 // regions bound in the obligation). Still probably some
2861 // refactoring could make this nicer.
2863 ty
::Binder(trait_ref
)
2866 fn closure_trait_ref(&mut self,
2867 obligation
: &TraitObligation
<'tcx
>,
2868 closure_def_id
: DefId
,
2869 substs
: &ty
::ClosureSubsts
<'tcx
>)
2870 -> Normalized
<'tcx
, ty
::PolyTraitRef
<'tcx
>>
2872 let trait_ref
= self.closure_trait_ref_unnormalized(
2873 obligation
, closure_def_id
, substs
);
2875 // A closure signature can contain associated types which
2876 // must be normalized.
2877 normalize_with_depth(self,
2878 obligation
.cause
.clone(),
2879 obligation
.recursion_depth
+1,
2883 /// Returns the obligations that are implied by instantiating an
2884 /// impl or trait. The obligations are substituted and fully
2885 /// normalized. This is used when confirming an impl or default
2887 fn impl_or_trait_obligations(&mut self,
2888 cause
: ObligationCause
<'tcx
>,
2889 recursion_depth
: usize,
2890 def_id
: DefId
, // of impl or trait
2891 substs
: &Substs
<'tcx
>, // for impl or trait
2892 skol_map
: infer
::SkolemizationMap
,
2893 snapshot
: &infer
::CombinedSnapshot
)
2894 -> Vec
<PredicateObligation
<'tcx
>>
2896 debug
!("impl_or_trait_obligations(def_id={:?})", def_id
);
2898 let predicates
= self.tcx().lookup_predicates(def_id
);
2899 let predicates
= predicates
.instantiate(self.tcx(), substs
);
2900 let predicates
= normalize_with_depth(self, cause
.clone(), recursion_depth
, &predicates
);
2901 let mut predicates
= self.infcx().plug_leaks(skol_map
, snapshot
, &predicates
);
2902 let mut obligations
=
2903 util
::predicates_for_generics(cause
,
2906 obligations
.append(&mut predicates
.obligations
);
2910 #[allow(unused_comparisons)]
2911 fn derived_cause(&self,
2912 obligation
: &TraitObligation
<'tcx
>,
2913 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>)
2914 -> ObligationCause
<'tcx
>
2917 * Creates a cause for obligations that are derived from
2918 * `obligation` by a recursive search (e.g., for a builtin
2919 * bound, or eventually a `impl Foo for ..`). If `obligation`
2920 * is itself a derived obligation, this is just a clone, but
2921 * otherwise we create a "derived obligation" cause so as to
2922 * keep track of the original root obligation for error
2926 // NOTE(flaper87): As of now, it keeps track of the whole error
2927 // chain. Ideally, we should have a way to configure this either
2928 // by using -Z verbose or just a CLI argument.
2929 if obligation
.recursion_depth
>= 0 {
2930 let derived_code
= match obligation
.cause
.code
{
2931 ObligationCauseCode
::RFC1214(ref base_code
) => {
2932 let derived_cause
= DerivedObligationCause
{
2933 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2934 parent_code
: base_code
.clone(),
2936 ObligationCauseCode
::RFC1214(Rc
::new(variant(derived_cause
)))
2939 let derived_cause
= DerivedObligationCause
{
2940 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2941 parent_code
: Rc
::new(obligation
.cause
.code
.clone())
2943 variant(derived_cause
)
2946 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2948 obligation
.cause
.clone()
2953 impl<'tcx
> SelectionCache
<'tcx
> {
2954 pub fn new() -> SelectionCache
<'tcx
> {
2956 hashmap
: RefCell
::new(FnvHashMap())
2961 impl<'o
,'tcx
> TraitObligationStack
<'o
,'tcx
> {
2962 fn list(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2963 TraitObligationStackList
::with(self)
2966 fn iter(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2971 #[derive(Copy, Clone)]
2972 struct TraitObligationStackList
<'o
,'tcx
:'o
> {
2973 head
: Option
<&'o TraitObligationStack
<'o
,'tcx
>>
2976 impl<'o
,'tcx
> TraitObligationStackList
<'o
,'tcx
> {
2977 fn empty() -> TraitObligationStackList
<'o
,'tcx
> {
2978 TraitObligationStackList { head: None }
2981 fn with(r
: &'o TraitObligationStack
<'o
,'tcx
>) -> TraitObligationStackList
<'o
,'tcx
> {
2982 TraitObligationStackList { head: Some(r) }
2986 impl<'o
,'tcx
> Iterator
for TraitObligationStackList
<'o
,'tcx
>{
2987 type Item
= &'o TraitObligationStack
<'o
,'tcx
>;
2989 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
,'tcx
>> {
3000 impl<'o
,'tcx
> fmt
::Debug
for TraitObligationStack
<'o
,'tcx
> {
3001 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
3002 write
!(f
, "TraitObligationStack({:?})", self.obligation
)
3006 impl<'tcx
> EvaluationResult
<'tcx
> {
3007 fn may_apply(&self) -> bool
{
3011 EvaluatedToErr(OutputTypeParameterMismatch(..)) |
3012 EvaluatedToErr(TraitNotObjectSafe(_
)) =>
3015 EvaluatedToErr(Unimplemented
) =>
3021 impl MethodMatchResult
{
3022 pub fn may_apply(&self) -> bool
{
3024 MethodMatched(_
) => true,
3025 MethodAmbiguous(_
) => true,
3026 MethodDidNotMatch
=> false,