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
13 pub use self::MethodMatchResult
::*;
14 pub use self::MethodMatchedData
::*;
15 use self::SelectionCandidate
::*;
16 use self::BuiltinBoundConditions
::*;
17 use self::EvaluationResult
::*;
20 use super::DerivedObligationCause
;
22 use super::project
::{normalize_with_depth, Normalized}
;
23 use super::{PredicateObligation, TraitObligation, ObligationCause}
;
24 use super::report_overflow_error
;
25 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation}
;
26 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch}
;
27 use super::{ObjectCastObligation, Obligation}
;
28 use super::ProjectionMode
;
29 use super::TraitNotObjectSafe
;
31 use super::SelectionResult
;
32 use super::{VtableBuiltin
, VtableImpl
, VtableParam
, VtableClosure
,
33 VtableFnPointer
, VtableObject
, VtableDefaultImpl
};
34 use super::{VtableImplData
, VtableObjectData
, VtableBuiltinData
,
35 VtableClosureData
, VtableDefaultImplData
};
36 use super::object_safety
;
39 use hir
::def_id
::DefId
;
41 use infer
::{InferCtxt, InferOk, TypeFreshener, TypeOrigin}
;
42 use ty
::subst
::{Subst, Substs, TypeSpace}
;
43 use ty
::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable}
;
46 use ty
::relate
::TypeRelation
;
48 use std
::cell
::RefCell
;
53 use util
::common
::ErrorReported
;
54 use util
::nodemap
::FnvHashMap
;
56 pub struct SelectionContext
<'cx
, 'tcx
:'cx
> {
57 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
59 /// Freshener used specifically for skolemizing entries on the
60 /// obligation stack. This ensures that all entries on the stack
61 /// at one time will have the same set of skolemized entries,
62 /// which is important for checking for trait bounds that
63 /// recursively require themselves.
64 freshener
: TypeFreshener
<'cx
, 'tcx
>,
66 /// If true, indicates that the evaluation should be conservative
67 /// and consider the possibility of types outside this crate.
68 /// This comes up primarily when resolving ambiguity. Imagine
69 /// there is some trait reference `$0 : Bar` where `$0` is an
70 /// inference variable. If `intercrate` is true, then we can never
71 /// say for sure that this reference is not implemented, even if
72 /// there are *no impls at all for `Bar`*, because `$0` could be
73 /// bound to some type that in a downstream crate that implements
74 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
75 /// though, we set this to false, because we are only interested
76 /// in types that the user could actually have written --- in
77 /// other words, we consider `$0 : Bar` to be unimplemented if
78 /// there is no type that the user could *actually name* that
79 /// would satisfy it. This avoids crippling inference, basically.
83 // A stack that walks back up the stack frame.
84 struct TraitObligationStack
<'prev
, 'tcx
: 'prev
> {
85 obligation
: &'prev TraitObligation
<'tcx
>,
87 /// Trait ref from `obligation` but skolemized with the
88 /// selection-context's freshener. Used to check for recursion.
89 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
91 previous
: TraitObligationStackList
<'prev
, 'tcx
>,
95 pub struct SelectionCache
<'tcx
> {
96 hashmap
: RefCell
<FnvHashMap
<ty
::TraitRef
<'tcx
>,
97 SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>>,
100 pub enum MethodMatchResult
{
101 MethodMatched(MethodMatchedData
),
102 MethodAmbiguous(/* list of impls that could apply */ Vec
<DefId
>),
106 #[derive(Copy, Clone, Debug)]
107 pub enum MethodMatchedData
{
108 // In the case of a precise match, we don't really need to store
109 // how the match was found. So don't.
112 // In the case of a coercion, we need to know the precise impl so
113 // that we can determine the type to which things were coerced.
114 CoerciveMethodMatch(/* impl we matched */ DefId
)
117 /// The selection process begins by considering all impls, where
118 /// clauses, and so forth that might resolve an obligation. Sometimes
119 /// we'll be able to say definitively that (e.g.) an impl does not
120 /// apply to the obligation: perhaps it is defined for `usize` but the
121 /// obligation is for `int`. In that case, we drop the impl out of the
122 /// list. But the other cases are considered *candidates*.
124 /// For selection to succeed, there must be exactly one matching
125 /// candidate. If the obligation is fully known, this is guaranteed
126 /// by coherence. However, if the obligation contains type parameters
127 /// or variables, there may be multiple such impls.
129 /// It is not a real problem if multiple matching impls exist because
130 /// of type variables - it just means the obligation isn't sufficiently
131 /// elaborated. In that case we report an ambiguity, and the caller can
132 /// try again after more type information has been gathered or report a
133 /// "type annotations required" error.
135 /// However, with type parameters, this can be a real problem - type
136 /// parameters don't unify with regular types, but they *can* unify
137 /// with variables from blanket impls, and (unless we know its bounds
138 /// will always be satisfied) picking the blanket impl will be wrong
139 /// for at least *some* substitutions. To make this concrete, if we have
141 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
142 /// impl<T: fmt::Debug> AsDebug for T {
144 /// fn debug(self) -> fmt::Debug { self }
146 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
148 /// we can't just use the impl to resolve the <T as AsDebug> obligation
149 /// - a type from another crate (that doesn't implement fmt::Debug) could
150 /// implement AsDebug.
152 /// Because where-clauses match the type exactly, multiple clauses can
153 /// only match if there are unresolved variables, and we can mostly just
154 /// report this ambiguity in that case. This is still a problem - we can't
155 /// *do anything* with ambiguities that involve only regions. This is issue
158 /// If a single where-clause matches and there are no inference
159 /// variables left, then it definitely matches and we can just select
162 /// In fact, we even select the where-clause when the obligation contains
163 /// inference variables. The can lead to inference making "leaps of logic",
164 /// for example in this situation:
166 /// pub trait Foo<T> { fn foo(&self) -> T; }
167 /// impl<T> Foo<()> for T { fn foo(&self) { } }
168 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
170 /// pub fn foo<T>(t: T) where T: Foo<bool> {
171 /// println!("{:?}", <T as Foo<_>>::foo(&t));
173 /// fn main() { foo(false); }
175 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
176 /// impl and the where-clause. We select the where-clause and unify $0=bool,
177 /// so the program prints "false". However, if the where-clause is omitted,
178 /// the blanket impl is selected, we unify $0=(), and the program prints
181 /// Exactly the same issues apply to projection and object candidates, except
182 /// that we can have both a projection candidate and a where-clause candidate
183 /// for the same obligation. In that case either would do (except that
184 /// different "leaps of logic" would occur if inference variables are
185 /// present), and we just pick the where-clause. This is, for example,
186 /// required for associated types to work in default impls, as the bounds
187 /// are visible both as projection bounds and as where-clauses from the
188 /// parameter environment.
189 #[derive(PartialEq,Eq,Debug,Clone)]
190 enum SelectionCandidate
<'tcx
> {
191 BuiltinCandidate(ty
::BuiltinBound
),
192 ParamCandidate(ty
::PolyTraitRef
<'tcx
>),
193 ImplCandidate(DefId
),
194 DefaultImplCandidate(DefId
),
195 DefaultImplObjectCandidate(DefId
),
197 /// This is a trait matching with a projected type as `Self`, and
198 /// we found an applicable bound in the trait definition.
201 /// Implementation of a `Fn`-family trait by one of the
202 /// anonymous types generated for a `||` expression.
203 ClosureCandidate(/* closure */ DefId
, &'tcx ty
::ClosureSubsts
<'tcx
>),
205 /// Implementation of a `Fn`-family trait by one of the anonymous
206 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
211 BuiltinObjectCandidate
,
213 BuiltinUnsizeCandidate
,
216 struct SelectionCandidateSet
<'tcx
> {
217 // a list of candidates that definitely apply to the current
218 // obligation (meaning: types unify).
219 vec
: Vec
<SelectionCandidate
<'tcx
>>,
221 // if this is true, then there were candidates that might or might
222 // not have applied, but we couldn't tell. This occurs when some
223 // of the input types are type variables, in which case there are
224 // various "builtin" rules that might or might not trigger.
228 #[derive(PartialEq,Eq,Debug,Clone)]
229 struct EvaluatedCandidate
<'tcx
> {
230 candidate
: SelectionCandidate
<'tcx
>,
231 evaluation
: EvaluationResult
,
234 enum BuiltinBoundConditions
<'tcx
> {
235 If(ty
::Binder
<Vec
<Ty
<'tcx
>>>),
240 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
241 /// The result of trait evaluation. The order is important
242 /// here as the evaluation of a list is the maximum of the
244 enum EvaluationResult
{
245 /// Evaluation successful
247 /// Evaluation failed because of recursion - treated as ambiguous
249 /// Evaluation is known to be ambiguous
251 /// Evaluation failed
256 pub struct EvaluationCache
<'tcx
> {
257 hashmap
: RefCell
<FnvHashMap
<ty
::PolyTraitRef
<'tcx
>, EvaluationResult
>>
260 impl<'cx
, 'tcx
> SelectionContext
<'cx
, 'tcx
> {
261 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
264 freshener
: infcx
.freshener(),
269 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'tcx
>) -> SelectionContext
<'cx
, 'tcx
> {
272 freshener
: infcx
.freshener(),
277 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
281 pub fn tcx(&self) -> &'cx TyCtxt
<'tcx
> {
285 pub fn param_env(&self) -> &'cx ty
::ParameterEnvironment
<'cx
, 'tcx
> {
286 self.infcx
.param_env()
289 pub fn closure_typer(&self) -> &'cx InferCtxt
<'cx
, 'tcx
> {
293 pub fn projection_mode(&self) -> ProjectionMode
{
294 self.infcx
.projection_mode()
297 ///////////////////////////////////////////////////////////////////////////
300 // The selection phase tries to identify *how* an obligation will
301 // be resolved. For example, it will identify which impl or
302 // parameter bound is to be used. The process can be inconclusive
303 // if the self type in the obligation is not fully inferred. Selection
304 // can result in an error in one of two ways:
306 // 1. If no applicable impl or parameter bound can be found.
307 // 2. If the output type parameters in the obligation do not match
308 // those specified by the impl/bound. For example, if the obligation
309 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
310 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
312 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
313 /// type environment by performing unification.
314 pub fn select(&mut self, obligation
: &TraitObligation
<'tcx
>)
315 -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
316 debug
!("select({:?})", obligation
);
317 assert
!(!obligation
.predicate
.has_escaping_regions());
319 let dep_node
= obligation
.predicate
.dep_node();
320 let _task
= self.tcx().dep_graph
.in_task(dep_node
);
322 let stack
= self.push_stack(TraitObligationStackList
::empty(), obligation
);
323 match self.candidate_from_obligation(&stack
)?
{
325 self.consider_unification_despite_ambiguity(obligation
);
328 Some(candidate
) => Ok(Some(self.confirm_candidate(obligation
, candidate
)?
)),
332 /// In the particular case of unboxed closure obligations, we can
333 /// sometimes do some amount of unification for the
334 /// argument/return types even though we can't yet fully match obligation.
335 /// The particular case we are interesting in is an obligation of the form:
339 /// where `C` is an unboxed closure type and `FnFoo` is one of the
340 /// `Fn` traits. Because we know that users cannot write impls for closure types
341 /// themselves, the only way that `C : FnFoo` can fail to match is under two
344 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
345 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
346 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
348 /// In either case, we always know what argument types are
349 /// expected by `C`, no matter what kind of `Fn` trait it
350 /// eventually matches. So we can go ahead and unify the argument
351 /// types, even though the end result is ambiguous.
353 /// Note that this is safe *even if* the trait would never be
354 /// matched (case 2 above). After all, in that case, an error will
355 /// result, so it kind of doesn't matter what we do --- unifying
356 /// the argument types can only be helpful to the user, because
357 /// once they patch up the kind of closure that is expected, the
358 /// argment types won't really change.
359 fn consider_unification_despite_ambiguity(&mut self, obligation
: &TraitObligation
<'tcx
>) {
360 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
361 match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
366 // Is the self-type a closure type? We ignore bindings here
367 // because if it is a closure type, it must be a closure type from
368 // within this current fn, and hence none of the higher-ranked
369 // lifetimes can appear inside the self-type.
370 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
371 let (closure_def_id
, substs
) = match self_ty
.sty
{
372 ty
::TyClosure(id
, ref substs
) => (id
, substs
),
375 assert
!(!substs
.has_escaping_regions());
377 // It is OK to call the unnormalized variant here - this is only
378 // reached for TyClosure: Fn inputs where the closure kind is
379 // still unknown, which should only occur in typeck where the
380 // closure type is already normalized.
381 let closure_trait_ref
= self.closure_trait_ref_unnormalized(obligation
,
385 match self.confirm_poly_trait_refs(obligation
.cause
.clone(),
386 obligation
.predicate
.to_poly_trait_ref(),
389 Err(_
) => { /* Silently ignore errors. */ }
393 ///////////////////////////////////////////////////////////////////////////
396 // Tests whether an obligation can be selected or whether an impl
397 // can be applied to particular types. It skips the "confirmation"
398 // step and hence completely ignores output type parameters.
400 // The result is "true" if the obligation *may* hold and "false" if
401 // we can be sure it does not.
403 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
404 pub fn evaluate_obligation(&mut self,
405 obligation
: &PredicateObligation
<'tcx
>)
408 debug
!("evaluate_obligation({:?})",
411 self.infcx
.probe(|_
| {
412 self.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
417 /// Evaluates whether the obligation `obligation` can be satisfied,
418 /// and returns `false` if not certain. However, this is not entirely
419 /// accurate if inference variables are involved.
420 pub fn evaluate_obligation_conservatively(&mut self,
421 obligation
: &PredicateObligation
<'tcx
>)
424 debug
!("evaluate_obligation_conservatively({:?})",
427 self.infcx
.probe(|_
| {
428 self.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
433 /// Evaluates the predicates in `predicates` recursively. Note that
434 /// this applies projections in the predicates, and therefore
435 /// is run within an inference probe.
436 fn evaluate_predicates_recursively
<'a
,'o
,I
>(&mut self,
437 stack
: TraitObligationStackList
<'o
, 'tcx
>,
440 where I
: Iterator
<Item
=&'a PredicateObligation
<'tcx
>>, 'tcx
:'a
442 let mut result
= EvaluatedToOk
;
443 for obligation
in predicates
{
444 let eval
= self.evaluate_predicate_recursively(stack
, obligation
);
445 debug
!("evaluate_predicate_recursively({:?}) = {:?}",
448 EvaluatedToErr
=> { return EvaluatedToErr; }
449 EvaluatedToAmbig
=> { result = EvaluatedToAmbig; }
450 EvaluatedToUnknown
=> {
451 if result
< EvaluatedToUnknown
{
452 result
= EvaluatedToUnknown
;
461 fn evaluate_predicate_recursively
<'o
>(&mut self,
462 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
463 obligation
: &PredicateObligation
<'tcx
>)
466 debug
!("evaluate_predicate_recursively({:?})",
469 // Check the cache from the tcx of predicates that we know
470 // have been proven elsewhere. This cache only contains
471 // predicates that are global in scope and hence unaffected by
472 // the current environment.
473 if self.tcx().fulfilled_predicates
.borrow().check_duplicate(&obligation
.predicate
) {
474 return EvaluatedToOk
;
477 match obligation
.predicate
{
478 ty
::Predicate
::Trait(ref t
) => {
479 assert
!(!t
.has_escaping_regions());
480 let obligation
= obligation
.with(t
.clone());
481 self.evaluate_obligation_recursively(previous_stack
, &obligation
)
484 ty
::Predicate
::Equate(ref p
) => {
485 // does this code ever run?
486 match self.infcx
.equality_predicate(obligation
.cause
.span
, p
) {
487 Ok(InferOk { obligations, .. }
) => {
488 // FIXME(#32730) propagate obligations
489 assert
!(obligations
.is_empty());
492 Err(_
) => EvaluatedToErr
496 ty
::Predicate
::WellFormed(ty
) => {
497 match ty
::wf
::obligations(self.infcx
, obligation
.cause
.body_id
,
498 ty
, obligation
.cause
.span
) {
500 self.evaluate_predicates_recursively(previous_stack
, obligations
.iter()),
506 ty
::Predicate
::TypeOutlives(..) | ty
::Predicate
::RegionOutlives(..) => {
507 // we do not consider region relationships when
508 // evaluating trait matches
512 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
513 if object_safety
::is_object_safe(self.tcx(), trait_def_id
) {
520 ty
::Predicate
::Projection(ref data
) => {
521 let project_obligation
= obligation
.with(data
.clone());
522 match project
::poly_project_and_unify_type(self, &project_obligation
) {
523 Ok(Some(subobligations
)) => {
524 self.evaluate_predicates_recursively(previous_stack
,
525 subobligations
.iter())
538 fn evaluate_obligation_recursively
<'o
>(&mut self,
539 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
540 obligation
: &TraitObligation
<'tcx
>)
543 debug
!("evaluate_obligation_recursively({:?})",
546 let stack
= self.push_stack(previous_stack
, obligation
);
547 let fresh_trait_ref
= stack
.fresh_trait_ref
;
548 if let Some(result
) = self.check_evaluation_cache(fresh_trait_ref
) {
549 debug
!("CACHE HIT: EVAL({:?})={:?}",
555 let result
= self.evaluate_stack(&stack
);
557 debug
!("CACHE MISS: EVAL({:?})={:?}",
560 self.insert_evaluation_cache(fresh_trait_ref
, result
);
565 fn evaluate_stack
<'o
>(&mut self,
566 stack
: &TraitObligationStack
<'o
, 'tcx
>)
569 // In intercrate mode, whenever any of the types are unbound,
570 // there can always be an impl. Even if there are no impls in
571 // this crate, perhaps the type would be unified with
572 // something from another crate that does provide an impl.
574 // In intra mode, we must still be conservative. The reason is
575 // that we want to avoid cycles. Imagine an impl like:
577 // impl<T:Eq> Eq for Vec<T>
579 // and a trait reference like `$0 : Eq` where `$0` is an
580 // unbound variable. When we evaluate this trait-reference, we
581 // will unify `$0` with `Vec<$1>` (for some fresh variable
582 // `$1`), on the condition that `$1 : Eq`. We will then wind
583 // up with many candidates (since that are other `Eq` impls
584 // that apply) and try to winnow things down. This results in
585 // a recursive evaluation that `$1 : Eq` -- as you can
586 // imagine, this is just where we started. To avoid that, we
587 // check for unbound variables and return an ambiguous (hence possible)
588 // match if we've seen this trait before.
590 // This suffices to allow chains like `FnMut` implemented in
591 // terms of `Fn` etc, but we could probably make this more
593 let input_types
= stack
.fresh_trait_ref
.0.input_types
();
594 let unbound_input_types
= input_types
.iter().any(|ty
| ty
.is_fresh());
595 if unbound_input_types
&& self.intercrate
{
596 debug
!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
597 stack
.fresh_trait_ref
);
598 return EvaluatedToAmbig
;
600 if unbound_input_types
&&
601 stack
.iter().skip(1).any(
602 |prev
| self.match_fresh_trait_refs(&stack
.fresh_trait_ref
,
603 &prev
.fresh_trait_ref
))
605 debug
!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
606 stack
.fresh_trait_ref
);
607 return EvaluatedToUnknown
;
610 // If there is any previous entry on the stack that precisely
611 // matches this obligation, then we can assume that the
612 // obligation is satisfied for now (still all other conditions
613 // must be met of course). One obvious case this comes up is
614 // marker traits like `Send`. Think of a linked list:
616 // struct List<T> { data: T, next: Option<Box<List<T>>> {
618 // `Box<List<T>>` will be `Send` if `T` is `Send` and
619 // `Option<Box<List<T>>>` is `Send`, and in turn
620 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
623 // Note that we do this comparison using the `fresh_trait_ref`
624 // fields. Because these have all been skolemized using
625 // `self.freshener`, we can be sure that (a) this will not
626 // affect the inferencer state and (b) that if we see two
627 // skolemized types with the same index, they refer to the
628 // same unbound type variable.
631 .skip(1) // skip top-most frame
632 .any(|prev
| stack
.fresh_trait_ref
== prev
.fresh_trait_ref
)
634 debug
!("evaluate_stack({:?}) --> recursive",
635 stack
.fresh_trait_ref
);
636 return EvaluatedToOk
;
639 match self.candidate_from_obligation(stack
) {
640 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
641 Ok(None
) => EvaluatedToAmbig
,
642 Err(..) => EvaluatedToErr
646 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
647 /// obligations are met. Returns true if `candidate` remains viable after this further
649 fn evaluate_candidate
<'o
>(&mut self,
650 stack
: &TraitObligationStack
<'o
, 'tcx
>,
651 candidate
: &SelectionCandidate
<'tcx
>)
654 debug
!("evaluate_candidate: depth={} candidate={:?}",
655 stack
.obligation
.recursion_depth
, candidate
);
656 let result
= self.infcx
.probe(|_
| {
657 let candidate
= (*candidate
).clone();
658 match self.confirm_candidate(stack
.obligation
, candidate
) {
660 self.evaluate_predicates_recursively(
662 selection
.nested_obligations().iter())
664 Err(..) => EvaluatedToErr
667 debug
!("evaluate_candidate: depth={} result={:?}",
668 stack
.obligation
.recursion_depth
, result
);
672 fn pick_evaluation_cache(&self) -> &EvaluationCache
<'tcx
> {
673 // see comment in `pick_candidate_cache`
674 if self.intercrate
||
675 !self.param_env().caller_bounds
.is_empty()
677 &self.param_env().evaluation_cache
680 &self.tcx().evaluation_cache
684 fn check_evaluation_cache(&self, trait_ref
: ty
::PolyTraitRef
<'tcx
>)
685 -> Option
<EvaluationResult
>
687 let cache
= self.pick_evaluation_cache();
688 cache
.hashmap
.borrow().get(&trait_ref
).cloned()
691 fn insert_evaluation_cache(&mut self,
692 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
693 result
: EvaluationResult
)
695 // Avoid caching results that depend on more than just the trait-ref:
696 // The stack can create EvaluatedToUnknown, and closure signatures
697 // being yet uninferred can create "spurious" EvaluatedToAmbig
698 // and EvaluatedToOk.
699 if result
== EvaluatedToUnknown
||
700 ((result
== EvaluatedToAmbig
|| result
== EvaluatedToOk
)
701 && trait_ref
.has_closure_types())
706 let cache
= self.pick_evaluation_cache();
707 cache
.hashmap
.borrow_mut().insert(trait_ref
, result
);
710 ///////////////////////////////////////////////////////////////////////////
711 // CANDIDATE ASSEMBLY
713 // The selection process begins by examining all in-scope impls,
714 // caller obligations, and so forth and assembling a list of
715 // candidates. See `README.md` and the `Candidate` type for more
718 fn candidate_from_obligation
<'o
>(&mut self,
719 stack
: &TraitObligationStack
<'o
, 'tcx
>)
720 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
722 // Watch out for overflow. This intentionally bypasses (and does
723 // not update) the cache.
724 let recursion_limit
= self.infcx
.tcx
.sess
.recursion_limit
.get();
725 if stack
.obligation
.recursion_depth
>= recursion_limit
{
726 report_overflow_error(self.infcx(), &stack
.obligation
, true);
729 // Check the cache. Note that we skolemize the trait-ref
730 // separately rather than using `stack.fresh_trait_ref` -- this
731 // is because we want the unbound variables to be replaced
732 // with fresh skolemized types starting from index 0.
733 let cache_fresh_trait_pred
=
734 self.infcx
.freshen(stack
.obligation
.predicate
.clone());
735 debug
!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
736 cache_fresh_trait_pred
,
738 assert
!(!stack
.obligation
.predicate
.has_escaping_regions());
740 match self.check_candidate_cache(&cache_fresh_trait_pred
) {
742 debug
!("CACHE HIT: SELECT({:?})={:?}",
743 cache_fresh_trait_pred
,
750 // If no match, compute result and insert into cache.
751 let candidate
= self.candidate_from_obligation_no_cache(stack
);
753 if self.should_update_candidate_cache(&cache_fresh_trait_pred
, &candidate
) {
754 debug
!("CACHE MISS: SELECT({:?})={:?}",
755 cache_fresh_trait_pred
, candidate
);
756 self.insert_candidate_cache(cache_fresh_trait_pred
, candidate
.clone());
762 // Treat negative impls as unimplemented
763 fn filter_negative_impls(&self, candidate
: SelectionCandidate
<'tcx
>)
764 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
765 if let ImplCandidate(def_id
) = candidate
{
766 if self.tcx().trait_impl_polarity(def_id
) == Some(hir
::ImplPolarity
::Negative
) {
767 return Err(Unimplemented
)
773 fn candidate_from_obligation_no_cache
<'o
>(&mut self,
774 stack
: &TraitObligationStack
<'o
, 'tcx
>)
775 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
777 if stack
.obligation
.predicate
.references_error() {
778 // If we encounter a `TyError`, we generally prefer the
779 // most "optimistic" result in response -- that is, the
780 // one least likely to report downstream errors. But
781 // because this routine is shared by coherence and by
782 // trait selection, there isn't an obvious "right" choice
783 // here in that respect, so we opt to just return
784 // ambiguity and let the upstream clients sort it out.
788 if !self.is_knowable(stack
) {
789 debug
!("coherence stage: not knowable");
793 let candidate_set
= self.assemble_candidates(stack
)?
;
795 if candidate_set
.ambiguous
{
796 debug
!("candidate set contains ambig");
800 let mut candidates
= candidate_set
.vec
;
802 debug
!("assembled {} candidates for {:?}: {:?}",
807 // At this point, we know that each of the entries in the
808 // candidate set is *individually* applicable. Now we have to
809 // figure out if they contain mutual incompatibilities. This
810 // frequently arises if we have an unconstrained input type --
811 // for example, we are looking for $0:Eq where $0 is some
812 // unconstrained type variable. In that case, we'll get a
813 // candidate which assumes $0 == int, one that assumes $0 ==
814 // usize, etc. This spells an ambiguity.
816 // If there is more than one candidate, first winnow them down
817 // by considering extra conditions (nested obligations and so
818 // forth). We don't winnow if there is exactly one
819 // candidate. This is a relatively minor distinction but it
820 // can lead to better inference and error-reporting. An
821 // example would be if there was an impl:
823 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
825 // and we were to see some code `foo.push_clone()` where `boo`
826 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
827 // we were to winnow, we'd wind up with zero candidates.
828 // Instead, we select the right impl now but report `Bar does
829 // not implement Clone`.
830 if candidates
.len() == 1 {
831 return self.filter_negative_impls(candidates
.pop().unwrap());
834 // Winnow, but record the exact outcome of evaluation, which
835 // is needed for specialization.
836 let mut candidates
: Vec
<_
> = candidates
.into_iter().filter_map(|c
| {
837 let eval
= self.evaluate_candidate(stack
, &c
);
838 if eval
.may_apply() {
839 Some(EvaluatedCandidate
{
848 // If there are STILL multiple candidate, we can further
849 // reduce the list by dropping duplicates -- including
850 // resolving specializations.
851 if candidates
.len() > 1 {
853 while i
< candidates
.len() {
855 (0..candidates
.len())
857 .any(|j
| self.candidate_should_be_dropped_in_favor_of(&candidates
[i
],
860 debug
!("Dropping candidate #{}/{}: {:?}",
861 i
, candidates
.len(), candidates
[i
]);
862 candidates
.swap_remove(i
);
864 debug
!("Retaining candidate #{}/{}: {:?}",
865 i
, candidates
.len(), candidates
[i
]);
871 // If there are *STILL* multiple candidates, give up and
873 if candidates
.len() > 1 {
874 debug
!("multiple matches, ambig");
878 // If there are *NO* candidates, then there are no impls --
879 // that we know of, anyway. Note that in the case where there
880 // are unbound type variables within the obligation, it might
881 // be the case that you could still satisfy the obligation
882 // from another crate by instantiating the type variables with
883 // a type from another crate that does have an impl. This case
884 // is checked for in `evaluate_stack` (and hence users
885 // who might care about this case, like coherence, should use
887 if candidates
.is_empty() {
888 return Err(Unimplemented
);
891 // Just one candidate left.
892 self.filter_negative_impls(candidates
.pop().unwrap().candidate
)
895 fn is_knowable
<'o
>(&mut self,
896 stack
: &TraitObligationStack
<'o
, 'tcx
>)
899 debug
!("is_knowable(intercrate={})", self.intercrate
);
901 if !self.intercrate
{
905 let obligation
= &stack
.obligation
;
906 let predicate
= self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
908 // ok to skip binder because of the nature of the
909 // trait-ref-is-knowable check, which does not care about
911 let trait_ref
= &predicate
.skip_binder().trait_ref
;
913 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
916 fn pick_candidate_cache(&self) -> &SelectionCache
<'tcx
> {
917 // If there are any where-clauses in scope, then we always use
918 // a cache local to this particular scope. Otherwise, we
919 // switch to a global cache. We used to try and draw
920 // finer-grained distinctions, but that led to a serious of
921 // annoying and weird bugs like #22019 and #18290. This simple
922 // rule seems to be pretty clearly safe and also still retains
923 // a very high hit rate (~95% when compiling rustc).
924 if !self.param_env().caller_bounds
.is_empty() {
925 return &self.param_env().selection_cache
;
928 // Avoid using the master cache during coherence and just rely
929 // on the local cache. This effectively disables caching
930 // during coherence. It is really just a simplification to
931 // avoid us having to fear that coherence results "pollute"
932 // the master cache. Since coherence executes pretty quickly,
933 // it's not worth going to more trouble to increase the
934 // hit-rate I don't think.
936 return &self.param_env().selection_cache
;
939 // Otherwise, we can use the global cache.
940 &self.tcx().selection_cache
943 fn check_candidate_cache(&mut self,
944 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>)
945 -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>
947 let cache
= self.pick_candidate_cache();
948 let hashmap
= cache
.hashmap
.borrow();
949 hashmap
.get(&cache_fresh_trait_pred
.0.trait_ref
).cloned()
952 fn insert_candidate_cache(&mut self,
953 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
954 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
956 let cache
= self.pick_candidate_cache();
957 let mut hashmap
= cache
.hashmap
.borrow_mut();
958 hashmap
.insert(cache_fresh_trait_pred
.0.trait_ref
.clone(), candidate
);
961 fn should_update_candidate_cache(&mut self,
962 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>,
963 candidate
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
966 // In general, it's a good idea to cache results, even
967 // ambiguous ones, to save us some trouble later. But we have
968 // to be careful not to cache results that could be
969 // invalidated later by advances in inference. Normally, this
970 // is not an issue, because any inference variables whose
971 // types are not yet bound are "freshened" in the cache key,
972 // which means that if we later get the same request once that
973 // type variable IS bound, we'll have a different cache key.
974 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
975 // not yet known, we may cache the result as `None`. But if
976 // later `_#0t` is bound to `Bar`, then when we freshen we'll
977 // have `Vec<Bar> : Foo` as the cache key.
979 // HOWEVER, it CAN happen that we get an ambiguity result in
980 // one particular case around closures where the cache key
981 // would not change. That is when the precise types of the
982 // upvars that a closure references have not yet been figured
983 // out (i.e., because it is not yet known if they are captured
984 // by ref, and if by ref, what kind of ref). In these cases,
985 // when matching a builtin bound, we will yield back an
986 // ambiguous result. But the *cache key* is just the closure type,
987 // it doesn't capture the state of the upvar computation.
989 // To avoid this trap, just don't cache ambiguous results if
990 // the self-type contains no inference byproducts (that really
991 // shouldn't happen in other circumstances anyway, given
995 Ok(Some(_
)) | Err(_
) => true,
997 cache_fresh_trait_pred
.0.trait_ref
.substs
.types
.has_infer_types()
1002 fn assemble_candidates
<'o
>(&mut self,
1003 stack
: &TraitObligationStack
<'o
, 'tcx
>)
1004 -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>>
1006 let TraitObligationStack { obligation, .. }
= *stack
;
1007 let ref obligation
= Obligation
{
1008 cause
: obligation
.cause
.clone(),
1009 recursion_depth
: obligation
.recursion_depth
,
1010 predicate
: self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
)
1013 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
1014 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1016 // This is somewhat problematic, as the current scheme can't really
1017 // handle it turning to be a projection. This does end up as truly
1018 // ambiguous in most cases anyway.
1020 // Until this is fixed, take the fast path out - this also improves
1021 // performance by preventing assemble_candidates_from_impls from
1022 // matching every impl for this trait.
1023 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
1026 let mut candidates
= SelectionCandidateSet
{
1031 // Other bounds. Consider both in-scope bounds from fn decl
1032 // and applicable impls. There is a certain set of precedence rules here.
1034 match self.tcx().lang_items
.to_builtin_kind(obligation
.predicate
.def_id()) {
1035 Some(ty
::BoundCopy
) => {
1036 debug
!("obligation self ty is {:?}",
1037 obligation
.predicate
.0.self_ty());
1039 // User-defined copy impls are permitted, but only for
1040 // structs and enums.
1041 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1043 // For other types, we'll use the builtin rules.
1044 self.assemble_builtin_bound_candidates(ty
::BoundCopy
,
1048 Some(bound @ ty
::BoundSized
) => {
1049 // Sized is never implementable by end-users, it is
1050 // always automatically computed.
1051 self.assemble_builtin_bound_candidates(bound
,
1056 None
if self.tcx().lang_items
.unsize_trait() ==
1057 Some(obligation
.predicate
.def_id()) => {
1058 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
1061 Some(ty
::BoundSend
) |
1062 Some(ty
::BoundSync
) |
1064 self.assemble_closure_candidates(obligation
, &mut candidates
)?
;
1065 self.assemble_fn_pointer_candidates(obligation
, &mut candidates
)?
;
1066 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1067 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
1071 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
1072 self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
)?
;
1073 // Default implementations have lower priority, so we only
1074 // consider triggering a default if there is no other impl that can apply.
1075 if candidates
.vec
.is_empty() {
1076 self.assemble_candidates_from_default_impls(obligation
, &mut candidates
)?
;
1078 debug
!("candidate list size: {}", candidates
.vec
.len());
1082 fn assemble_candidates_from_projected_tys(&mut self,
1083 obligation
: &TraitObligation
<'tcx
>,
1084 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1086 debug
!("assemble_candidates_for_projected_tys({:?})", obligation
);
1088 // FIXME(#20297) -- just examining the self-type is very simplistic
1090 // before we go into the whole skolemization thing, just
1091 // quickly check if the self-type is a projection at all.
1092 let trait_def_id
= match obligation
.predicate
.0.trait_ref
.self_ty().sty
{
1093 ty
::TyProjection(ref data
) => data
.trait_ref
.def_id
,
1094 ty
::TyInfer(ty
::TyVar(_
)) => {
1095 span_bug
!(obligation
.cause
.span
,
1096 "Self=_ should have been handled by assemble_candidates");
1101 debug
!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1104 let result
= self.infcx
.probe(|snapshot
| {
1105 self.match_projection_obligation_against_bounds_from_trait(obligation
,
1110 candidates
.vec
.push(ProjectionCandidate
);
1114 fn match_projection_obligation_against_bounds_from_trait(
1116 obligation
: &TraitObligation
<'tcx
>,
1117 snapshot
: &infer
::CombinedSnapshot
)
1120 let poly_trait_predicate
=
1121 self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
1122 let (skol_trait_predicate
, skol_map
) =
1123 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate
, snapshot
);
1124 debug
!("match_projection_obligation_against_bounds_from_trait: \
1125 skol_trait_predicate={:?} skol_map={:?}",
1126 skol_trait_predicate
,
1129 let projection_trait_ref
= match skol_trait_predicate
.trait_ref
.self_ty().sty
{
1130 ty
::TyProjection(ref data
) => &data
.trait_ref
,
1133 obligation
.cause
.span
,
1134 "match_projection_obligation_against_bounds_from_trait() called \
1135 but self-ty not a projection: {:?}",
1136 skol_trait_predicate
.trait_ref
.self_ty());
1139 debug
!("match_projection_obligation_against_bounds_from_trait: \
1140 projection_trait_ref={:?}",
1141 projection_trait_ref
);
1143 let trait_predicates
= self.tcx().lookup_predicates(projection_trait_ref
.def_id
);
1144 let bounds
= trait_predicates
.instantiate(self.tcx(), projection_trait_ref
.substs
);
1145 debug
!("match_projection_obligation_against_bounds_from_trait: \
1149 let matching_bound
=
1150 util
::elaborate_predicates(self.tcx(), bounds
.predicates
.into_vec())
1153 |bound
| self.infcx
.probe(
1154 |_
| self.match_projection(obligation
,
1156 skol_trait_predicate
.trait_ref
.clone(),
1160 debug
!("match_projection_obligation_against_bounds_from_trait: \
1161 matching_bound={:?}",
1163 match matching_bound
{
1166 // Repeat the successful match, if any, this time outside of a probe.
1167 let result
= self.match_projection(obligation
,
1169 skol_trait_predicate
.trait_ref
.clone(),
1178 fn match_projection(&mut self,
1179 obligation
: &TraitObligation
<'tcx
>,
1180 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1181 skol_trait_ref
: ty
::TraitRef
<'tcx
>,
1182 skol_map
: &infer
::SkolemizationMap
,
1183 snapshot
: &infer
::CombinedSnapshot
)
1186 assert
!(!skol_trait_ref
.has_escaping_regions());
1187 let origin
= TypeOrigin
::RelateOutputImplTypes(obligation
.cause
.span
);
1188 match self.infcx
.sub_poly_trait_refs(false,
1190 trait_bound
.clone(),
1191 ty
::Binder(skol_trait_ref
.clone())) {
1192 Ok(InferOk { obligations, .. }
) => {
1193 // FIXME(#32730) propagate obligations
1194 assert
!(obligations
.is_empty());
1196 Err(_
) => { return false; }
1199 self.infcx
.leak_check(skol_map
, snapshot
).is_ok()
1202 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1203 /// supplied to find out whether it is listed among them.
1205 /// Never affects inference environment.
1206 fn assemble_candidates_from_caller_bounds
<'o
>(&mut self,
1207 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1208 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1209 -> Result
<(),SelectionError
<'tcx
>>
1211 debug
!("assemble_candidates_from_caller_bounds({:?})",
1215 self.param_env().caller_bounds
1217 .filter_map(|o
| o
.to_opt_poly_trait_ref());
1219 let matching_bounds
=
1221 |bound
| self.evaluate_where_clause(stack
, bound
.clone()).may_apply());
1223 let param_candidates
=
1224 matching_bounds
.map(|bound
| ParamCandidate(bound
));
1226 candidates
.vec
.extend(param_candidates
);
1231 fn evaluate_where_clause
<'o
>(&mut self,
1232 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1233 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
1236 self.infcx().probe(move |_
| {
1237 match self.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1238 Ok(obligations
) => {
1239 self.evaluate_predicates_recursively(stack
.list(), obligations
.iter())
1241 Err(()) => EvaluatedToErr
1246 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1247 /// FnMut<..>` where `X` is a closure type.
1249 /// Note: the type parameters on a closure candidate are modeled as *output* type
1250 /// parameters and hence do not affect whether this trait is a match or not. They will be
1251 /// unified during the confirmation step.
1252 fn assemble_closure_candidates(&mut self,
1253 obligation
: &TraitObligation
<'tcx
>,
1254 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1255 -> Result
<(),SelectionError
<'tcx
>>
1257 let kind
= match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
1259 None
=> { return Ok(()); }
1262 // ok to skip binder because the substs on closure types never
1263 // touch bound regions, they just capture the in-scope
1264 // type/region parameters
1265 let self_ty
= *obligation
.self_ty().skip_binder();
1266 let (closure_def_id
, substs
) = match self_ty
.sty
{
1267 ty
::TyClosure(id
, ref substs
) => (id
, substs
),
1268 ty
::TyInfer(ty
::TyVar(_
)) => {
1269 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
1270 candidates
.ambiguous
= true;
1273 _
=> { return Ok(()); }
1276 debug
!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1281 match self.infcx
.closure_kind(closure_def_id
) {
1282 Some(closure_kind
) => {
1283 debug
!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind
);
1284 if closure_kind
.extends(kind
) {
1285 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
));
1289 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
1290 candidates
.ambiguous
= true;
1297 /// Implement one of the `Fn()` family for a fn pointer.
1298 fn assemble_fn_pointer_candidates(&mut self,
1299 obligation
: &TraitObligation
<'tcx
>,
1300 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1301 -> Result
<(),SelectionError
<'tcx
>>
1303 // We provide impl of all fn traits for fn pointers.
1304 if self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.def_id()).is_none() {
1308 // ok to skip binder because what we are inspecting doesn't involve bound regions
1309 let self_ty
= *obligation
.self_ty().skip_binder();
1311 ty
::TyInfer(ty
::TyVar(_
)) => {
1312 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
1313 candidates
.ambiguous
= true; // could wind up being a fn() type
1316 // provide an impl, but only for suitable `fn` pointers
1317 ty
::TyFnDef(_
, _
, &ty
::BareFnTy
{
1318 unsafety
: hir
::Unsafety
::Normal
,
1320 sig
: ty
::Binder(ty
::FnSig
{
1322 output
: ty
::FnConverging(_
),
1326 ty
::TyFnPtr(&ty
::BareFnTy
{
1327 unsafety
: hir
::Unsafety
::Normal
,
1329 sig
: ty
::Binder(ty
::FnSig
{
1331 output
: ty
::FnConverging(_
),
1335 candidates
.vec
.push(FnPointerCandidate
);
1344 /// Search for impls that might apply to `obligation`.
1345 fn assemble_candidates_from_impls(&mut self,
1346 obligation
: &TraitObligation
<'tcx
>,
1347 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1348 -> Result
<(), SelectionError
<'tcx
>>
1350 debug
!("assemble_candidates_from_impls(obligation={:?})", obligation
);
1352 let def
= self.tcx().lookup_trait_def(obligation
.predicate
.def_id());
1354 def
.for_each_relevant_impl(
1356 obligation
.predicate
.0.trait_ref
.self_ty(),
1358 self.infcx
.probe(|snapshot
| {
1359 if let Ok(_
) = self.match_impl(impl_def_id
, obligation
, snapshot
) {
1360 candidates
.vec
.push(ImplCandidate(impl_def_id
));
1369 fn assemble_candidates_from_default_impls(&mut self,
1370 obligation
: &TraitObligation
<'tcx
>,
1371 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1372 -> Result
<(), SelectionError
<'tcx
>>
1374 // OK to skip binder here because the tests we do below do not involve bound regions
1375 let self_ty
= *obligation
.self_ty().skip_binder();
1376 debug
!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty
);
1378 let def_id
= obligation
.predicate
.def_id();
1380 if self.tcx().trait_has_default_impl(def_id
) {
1382 ty
::TyTrait(..) => {
1383 // For object types, we don't know what the closed
1384 // over types are. For most traits, this means we
1385 // conservatively say nothing; a candidate may be
1386 // added by `assemble_candidates_from_object_ty`.
1387 // However, for the kind of magic reflect trait,
1388 // we consider it to be implemented even for
1389 // object types, because it just lets you reflect
1390 // onto the object type, not into the object's
1392 if self.tcx().has_attr(def_id
, "rustc_reflect_like") {
1393 candidates
.vec
.push(DefaultImplObjectCandidate(def_id
));
1397 ty
::TyProjection(..) => {
1398 // In these cases, we don't know what the actual
1399 // type is. Therefore, we cannot break it down
1400 // into its constituent types. So we don't
1401 // consider the `..` impl but instead just add no
1402 // candidates: this means that typeck will only
1403 // succeed if there is another reason to believe
1404 // that this obligation holds. That could be a
1405 // where-clause or, in the case of an object type,
1406 // it could be that the object type lists the
1407 // trait (e.g. `Foo+Send : Send`). See
1408 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1409 // for an example of a test case that exercises
1412 ty
::TyInfer(ty
::TyVar(_
)) => {
1413 // the defaulted impl might apply, we don't know
1414 candidates
.ambiguous
= true;
1417 candidates
.vec
.push(DefaultImplCandidate(def_id
.clone()))
1425 /// Search for impls that might apply to `obligation`.
1426 fn assemble_candidates_from_object_ty(&mut self,
1427 obligation
: &TraitObligation
<'tcx
>,
1428 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1430 debug
!("assemble_candidates_from_object_ty(self_ty={:?})",
1431 obligation
.self_ty().skip_binder());
1433 // Object-safety candidates are only applicable to object-safe
1434 // traits. Including this check is useful because it helps
1435 // inference in cases of traits like `BorrowFrom`, which are
1436 // not object-safe, and which rely on being able to infer the
1437 // self-type from one of the other inputs. Without this check,
1438 // these cases wind up being considered ambiguous due to a
1439 // (spurious) ambiguity introduced here.
1440 let predicate_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
1441 if !object_safety
::is_object_safe(self.tcx(), predicate_trait_ref
.def_id()) {
1445 self.infcx
.commit_if_ok(|snapshot
| {
1447 self.infcx().skolemize_late_bound_regions(&obligation
.self_ty(), snapshot
);
1448 let poly_trait_ref
= match self_ty
.sty
{
1449 ty
::TyTrait(ref data
) => {
1450 match self.tcx().lang_items
.to_builtin_kind(obligation
.predicate
.def_id()) {
1451 Some(bound @ ty
::BoundSend
) | Some(bound @ ty
::BoundSync
) => {
1452 if data
.bounds
.builtin_bounds
.contains(&bound
) {
1453 debug
!("assemble_candidates_from_object_ty: matched builtin bound, \
1454 pushing candidate");
1455 candidates
.vec
.push(BuiltinObjectCandidate
);
1462 data
.principal_trait_ref_with_self_ty(self.tcx(), self_ty
)
1464 ty
::TyInfer(ty
::TyVar(_
)) => {
1465 debug
!("assemble_candidates_from_object_ty: ambiguous");
1466 candidates
.ambiguous
= true; // could wind up being an object type
1474 debug
!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1477 // Count only those upcast versions that match the trait-ref
1478 // we are looking for. Specifically, do not only check for the
1479 // correct trait, but also the correct type parameters.
1480 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1481 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1482 let upcast_trait_refs
=
1483 util
::supertraits(self.tcx(), poly_trait_ref
)
1484 .filter(|upcast_trait_ref
| {
1485 self.infcx
.probe(|_
| {
1486 let upcast_trait_ref
= upcast_trait_ref
.clone();
1487 self.match_poly_trait_ref(obligation
, upcast_trait_ref
).is_ok()
1492 if upcast_trait_refs
> 1 {
1493 // can be upcast in many ways; need more type information
1494 candidates
.ambiguous
= true;
1495 } else if upcast_trait_refs
== 1 {
1496 candidates
.vec
.push(ObjectCandidate
);
1503 /// Search for unsizing that might apply to `obligation`.
1504 fn assemble_candidates_for_unsizing(&mut self,
1505 obligation
: &TraitObligation
<'tcx
>,
1506 candidates
: &mut SelectionCandidateSet
<'tcx
>) {
1507 // We currently never consider higher-ranked obligations e.g.
1508 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1509 // because they are a priori invalid, and we could potentially add support
1510 // for them later, it's just that there isn't really a strong need for it.
1511 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1512 // impl, and those are generally applied to concrete types.
1514 // That said, one might try to write a fn with a where clause like
1515 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1516 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1517 // Still, you'd be more likely to write that where clause as
1519 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1520 // obligation above. Should be possible to extend this in the future.
1521 let source
= match self.tcx().no_late_bound_regions(&obligation
.self_ty()) {
1524 // Don't add any candidates if there are bound regions.
1528 let target
= obligation
.predicate
.0.input_types
()[0];
1530 debug
!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1533 let may_apply
= match (&source
.sty
, &target
.sty
) {
1534 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1535 (&ty
::TyTrait(ref data_a
), &ty
::TyTrait(ref data_b
)) => {
1536 // Upcasts permit two things:
1538 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1539 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1541 // Note that neither of these changes requires any
1542 // change at runtime. Eventually this will be
1545 // We always upcast when we can because of reason
1546 // #2 (region bounds).
1547 data_a
.principal
.def_id() == data_a
.principal
.def_id() &&
1548 data_a
.bounds
.builtin_bounds
.is_superset(&data_b
.bounds
.builtin_bounds
)
1552 (_
, &ty
::TyTrait(_
)) => true,
1554 // Ambiguous handling is below T -> Trait, because inference
1555 // variables can still implement Unsize<Trait> and nested
1556 // obligations will have the final say (likely deferred).
1557 (&ty
::TyInfer(ty
::TyVar(_
)), _
) |
1558 (_
, &ty
::TyInfer(ty
::TyVar(_
))) => {
1559 debug
!("assemble_candidates_for_unsizing: ambiguous");
1560 candidates
.ambiguous
= true;
1565 (&ty
::TyArray(_
, _
), &ty
::TySlice(_
)) => true,
1567 // Struct<T> -> Struct<U>.
1568 (&ty
::TyStruct(def_id_a
, _
), &ty
::TyStruct(def_id_b
, _
)) => {
1569 def_id_a
== def_id_b
1576 candidates
.vec
.push(BuiltinUnsizeCandidate
);
1580 ///////////////////////////////////////////////////////////////////////////
1583 // Winnowing is the process of attempting to resolve ambiguity by
1584 // probing further. During the winnowing process, we unify all
1585 // type variables (ignoring skolemization) and then we also
1586 // attempt to evaluate recursive bounds to see if they are
1589 /// Returns true if `candidate_i` should be dropped in favor of
1590 /// `candidate_j`. Generally speaking we will drop duplicate
1591 /// candidates and prefer where-clause candidates.
1592 /// Returns true if `victim` should be dropped in favor of
1593 /// `other`. Generally speaking we will drop duplicate
1594 /// candidates and prefer where-clause candidates.
1596 /// See the comment for "SelectionCandidate" for more details.
1597 fn candidate_should_be_dropped_in_favor_of
<'o
>(
1599 victim
: &EvaluatedCandidate
<'tcx
>,
1600 other
: &EvaluatedCandidate
<'tcx
>)
1603 if victim
.candidate
== other
.candidate
{
1607 match other
.candidate
{
1609 ParamCandidate(_
) | ProjectionCandidate
=> match victim
.candidate
{
1610 DefaultImplCandidate(..) => {
1612 "default implementations shouldn't be recorded \
1613 when there are other valid candidates");
1616 ClosureCandidate(..) |
1617 FnPointerCandidate
|
1618 BuiltinObjectCandidate
|
1619 BuiltinUnsizeCandidate
|
1620 DefaultImplObjectCandidate(..) |
1621 BuiltinCandidate(..) => {
1622 // We have a where-clause so don't go around looking
1627 ProjectionCandidate
=> {
1628 // Arbitrarily give param candidates priority
1629 // over projection and object candidates.
1632 ParamCandidate(..) => false,
1634 ImplCandidate(other_def
) => {
1635 // See if we can toss out `victim` based on specialization.
1636 // This requires us to know *for sure* that the `other` impl applies
1637 // i.e. EvaluatedToOk:
1638 if other
.evaluation
== EvaluatedToOk
{
1639 if let ImplCandidate(victim_def
) = victim
.candidate
{
1640 return traits
::specializes(self.tcx(), other_def
, victim_def
);
1650 ///////////////////////////////////////////////////////////////////////////
1653 // These cover the traits that are built-in to the language
1654 // itself. This includes `Copy` and `Sized` for sure. For the
1655 // moment, it also includes `Send` / `Sync` and a few others, but
1656 // those will hopefully change to library-defined traits in the
1659 fn assemble_builtin_bound_candidates
<'o
>(&mut self,
1660 bound
: ty
::BuiltinBound
,
1661 obligation
: &TraitObligation
<'tcx
>,
1662 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1663 -> Result
<(),SelectionError
<'tcx
>>
1665 match self.builtin_bound(bound
, obligation
) {
1667 debug
!("builtin_bound: bound={:?}",
1669 candidates
.vec
.push(BuiltinCandidate(bound
));
1672 Ok(ParameterBuiltin
) => { Ok(()) }
1673 Ok(AmbiguousBuiltin
) => {
1674 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1675 Ok(candidates
.ambiguous
= true)
1677 Err(e
) => { Err(e) }
1681 fn builtin_bound(&mut self,
1682 bound
: ty
::BuiltinBound
,
1683 obligation
: &TraitObligation
<'tcx
>)
1684 -> Result
<BuiltinBoundConditions
<'tcx
>,SelectionError
<'tcx
>>
1686 // Note: these tests operate on types that may contain bound
1687 // regions. To be proper, we ought to skolemize here, but we
1688 // forego the skolemization and defer it until the
1689 // confirmation step.
1691 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.0.self_ty());
1692 return match self_ty
.sty
{
1693 ty
::TyInfer(ty
::IntVar(_
)) |
1694 ty
::TyInfer(ty
::FloatVar(_
)) |
1702 // safe for everything
1706 ty
::TyBox(_
) => { // Box<T>
1708 ty
::BoundCopy
=> Err(Unimplemented
),
1710 ty
::BoundSized
=> ok_if(Vec
::new()),
1712 ty
::BoundSync
| ty
::BoundSend
=> {
1713 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1718 ty
::TyRawPtr(..) => { // *const T, *mut T
1720 ty
::BoundCopy
| ty
::BoundSized
=> ok_if(Vec
::new()),
1722 ty
::BoundSync
| ty
::BoundSend
=> {
1723 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1728 ty
::TyTrait(ref data
) => {
1730 ty
::BoundSized
=> Err(Unimplemented
),
1732 if data
.bounds
.builtin_bounds
.contains(&bound
) {
1735 // Recursively check all supertraits to find out if any further
1736 // bounds are required and thus we must fulfill.
1738 data
.principal_trait_ref_with_self_ty(self.tcx(),
1739 self.tcx().types
.err
);
1740 let copy_def_id
= obligation
.predicate
.def_id();
1741 for tr
in util
::supertraits(self.tcx(), principal
) {
1742 if tr
.def_id() == copy_def_id
{
1743 return ok_if(Vec
::new())
1750 ty
::BoundSync
| ty
::BoundSend
=> {
1751 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1756 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl }
) => {
1761 // &mut T is affine and hence never `Copy`
1762 hir
::MutMutable
=> Err(Unimplemented
),
1764 // &T is always copyable
1765 hir
::MutImmutable
=> ok_if(Vec
::new()),
1769 ty
::BoundSized
=> ok_if(Vec
::new()),
1771 ty
::BoundSync
| ty
::BoundSend
=> {
1772 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1777 ty
::TyArray(element_ty
, _
) => {
1780 ty
::BoundCopy
=> ok_if(vec
![element_ty
]),
1781 ty
::BoundSized
=> ok_if(Vec
::new()),
1782 ty
::BoundSync
| ty
::BoundSend
=> {
1783 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1788 ty
::TyStr
| ty
::TySlice(_
) => {
1790 ty
::BoundSync
| ty
::BoundSend
=> {
1791 bug
!("Send/Sync shouldn't occur in builtin_bounds()");
1794 ty
::BoundCopy
| ty
::BoundSized
=> Err(Unimplemented
),
1798 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1799 ty
::TyTuple(ref tys
) => ok_if(tys
.clone()),
1801 ty
::TyClosure(_
, ref substs
) => {
1802 // FIXME -- This case is tricky. In the case of by-ref
1803 // closures particularly, we need the results of
1804 // inference to decide how to reflect the type of each
1805 // upvar (the upvar may have type `T`, but the runtime
1806 // type could be `&mut`, `&`, or just `T`). For now,
1807 // though, we'll do this unsoundly and assume that all
1808 // captures are by value. Really what we ought to do
1809 // is reserve judgement and then intertwine this
1810 // analysis with closure inference.
1812 // Unboxed closures shouldn't be
1813 // implicitly copyable
1814 if bound
== ty
::BoundCopy
{
1815 return Ok(ParameterBuiltin
);
1818 // Upvars are always local variables or references to
1819 // local variables, and local variables cannot be
1820 // unsized, so the closure struct as a whole must be
1822 if bound
== ty
::BoundSized
{
1823 return ok_if(Vec
::new());
1826 ok_if(substs
.upvar_tys
.clone())
1829 ty
::TyStruct(def
, substs
) | ty
::TyEnum(def
, substs
) => {
1830 let types
: Vec
<Ty
> = def
.all_fields().map(|f
| {
1831 f
.ty(self.tcx(), substs
)
1833 nominal(bound
, types
)
1836 ty
::TyProjection(_
) | ty
::TyParam(_
) => {
1837 // Note: A type parameter is only considered to meet a
1838 // particular bound if there is a where clause telling
1839 // us that it does, and that case is handled by
1840 // `assemble_candidates_from_caller_bounds()`.
1841 Ok(ParameterBuiltin
)
1844 ty
::TyInfer(ty
::TyVar(_
)) => {
1845 // Unbound type variable. Might or might not have
1846 // applicable impls and so forth, depending on what
1847 // those type variables wind up being bound to.
1848 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1849 Ok(AmbiguousBuiltin
)
1852 ty
::TyError
=> ok_if(Vec
::new()),
1854 ty
::TyInfer(ty
::FreshTy(_
))
1855 | ty
::TyInfer(ty
::FreshIntTy(_
))
1856 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1857 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1862 fn ok_if
<'tcx
>(v
: Vec
<Ty
<'tcx
>>)
1863 -> Result
<BuiltinBoundConditions
<'tcx
>, SelectionError
<'tcx
>> {
1864 Ok(If(ty
::Binder(v
)))
1867 fn nominal
<'cx
, 'tcx
>(bound
: ty
::BuiltinBound
,
1868 types
: Vec
<Ty
<'tcx
>>)
1869 -> Result
<BuiltinBoundConditions
<'tcx
>, SelectionError
<'tcx
>>
1871 // First check for markers and other nonsense.
1873 // Fallback to whatever user-defined impls exist in this case.
1874 ty
::BoundCopy
=> Ok(ParameterBuiltin
),
1876 // Sized if all the component types are sized.
1877 ty
::BoundSized
=> ok_if(types
),
1879 // Shouldn't be coming through here.
1880 ty
::BoundSend
| ty
::BoundSync
=> bug
!(),
1885 /// For default impls, we need to break apart a type into its
1886 /// "constituent types" -- meaning, the types that it contains.
1888 /// Here are some (simple) examples:
1891 /// (i32, u32) -> [i32, u32]
1892 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1893 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1894 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1896 fn constituent_types_for_ty(&self, t
: Ty
<'tcx
>) -> Vec
<Ty
<'tcx
>> {
1906 ty
::TyInfer(ty
::IntVar(_
)) |
1907 ty
::TyInfer(ty
::FloatVar(_
)) |
1914 ty
::TyProjection(..) |
1915 ty
::TyInfer(ty
::TyVar(_
)) |
1916 ty
::TyInfer(ty
::FreshTy(_
)) |
1917 ty
::TyInfer(ty
::FreshIntTy(_
)) |
1918 ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1919 bug
!("asked to assemble constituent types of unexpected type: {:?}",
1923 ty
::TyBox(referent_ty
) => { // Box<T>
1927 ty
::TyRawPtr(ty
::TypeAndMut { ty: element_ty, ..}
) |
1928 ty
::TyRef(_
, ty
::TypeAndMut { ty: element_ty, ..}
) => {
1932 ty
::TyArray(element_ty
, _
) | ty
::TySlice(element_ty
) => {
1936 ty
::TyTuple(ref tys
) => {
1937 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1941 ty
::TyClosure(_
, ref substs
) => {
1942 // FIXME(#27086). We are invariant w/r/t our
1943 // substs.func_substs, but we don't see them as
1944 // constituent types; this seems RIGHT but also like
1945 // something that a normal type couldn't simulate. Is
1946 // this just a gap with the way that PhantomData and
1947 // OIBIT interact? That is, there is no way to say
1948 // "make me invariant with respect to this TYPE, but
1949 // do not act as though I can reach it"
1950 substs
.upvar_tys
.clone()
1953 // for `PhantomData<T>`, we pass `T`
1954 ty
::TyStruct(def
, substs
) if def
.is_phantom_data() => {
1955 substs
.types
.get_slice(TypeSpace
).to_vec()
1958 ty
::TyStruct(def
, substs
) | ty
::TyEnum(def
, substs
) => {
1960 .map(|f
| f
.ty(self.tcx(), substs
))
1966 fn collect_predicates_for_types(&mut self,
1967 obligation
: &TraitObligation
<'tcx
>,
1968 trait_def_id
: DefId
,
1969 types
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
1970 -> Vec
<PredicateObligation
<'tcx
>>
1972 let derived_cause
= match self.tcx().lang_items
.to_builtin_kind(trait_def_id
) {
1974 self.derived_cause(obligation
, BuiltinDerivedObligation
)
1977 self.derived_cause(obligation
, ImplDerivedObligation
)
1981 // Because the types were potentially derived from
1982 // higher-ranked obligations they may reference late-bound
1983 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1984 // yield a type like `for<'a> &'a int`. In general, we
1985 // maintain the invariant that we never manipulate bound
1986 // regions, so we have to process these bound regions somehow.
1988 // The strategy is to:
1990 // 1. Instantiate those regions to skolemized regions (e.g.,
1991 // `for<'a> &'a int` becomes `&0 int`.
1992 // 2. Produce something like `&'0 int : Copy`
1993 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1995 // Move the binder into the individual types
1996 let bound_types
: Vec
<ty
::Binder
<Ty
<'tcx
>>> =
1999 .map(|&nested_ty
| ty
::Binder(nested_ty
))
2002 // For each type, produce a vector of resulting obligations
2003 let obligations
: Result
<Vec
<Vec
<_
>>, _
> = bound_types
.iter().map(|nested_ty
| {
2004 self.infcx
.commit_if_ok(|snapshot
| {
2005 let (skol_ty
, skol_map
) =
2006 self.infcx().skolemize_late_bound_regions(nested_ty
, snapshot
);
2007 let Normalized { value: normalized_ty, mut obligations }
=
2008 project
::normalize_with_depth(self,
2009 obligation
.cause
.clone(),
2010 obligation
.recursion_depth
+ 1,
2012 let skol_obligation
=
2013 util
::predicate_for_trait_def(self.tcx(),
2014 derived_cause
.clone(),
2016 obligation
.recursion_depth
+ 1,
2019 obligations
.push(skol_obligation
);
2020 Ok(self.infcx().plug_leaks(skol_map
, snapshot
, &obligations
))
2024 // Flatten those vectors (couldn't do it above due `collect`)
2026 Ok(obligations
) => obligations
.into_iter().flat_map(|o
| o
).collect(),
2027 Err(ErrorReported
) => Vec
::new(),
2031 ///////////////////////////////////////////////////////////////////////////
2034 // Confirmation unifies the output type parameters of the trait
2035 // with the values found in the obligation, possibly yielding a
2036 // type error. See `README.md` for more details.
2038 fn confirm_candidate(&mut self,
2039 obligation
: &TraitObligation
<'tcx
>,
2040 candidate
: SelectionCandidate
<'tcx
>)
2041 -> Result
<Selection
<'tcx
>,SelectionError
<'tcx
>>
2043 debug
!("confirm_candidate({:?}, {:?})",
2048 BuiltinCandidate(builtin_bound
) => {
2050 self.confirm_builtin_candidate(obligation
, builtin_bound
)?
))
2053 ParamCandidate(param
) => {
2054 let obligations
= self.confirm_param_candidate(obligation
, param
);
2055 Ok(VtableParam(obligations
))
2058 DefaultImplCandidate(trait_def_id
) => {
2059 let data
= self.confirm_default_impl_candidate(obligation
, trait_def_id
);
2060 Ok(VtableDefaultImpl(data
))
2063 DefaultImplObjectCandidate(trait_def_id
) => {
2064 let data
= self.confirm_default_impl_object_candidate(obligation
, trait_def_id
);
2065 Ok(VtableDefaultImpl(data
))
2068 ImplCandidate(impl_def_id
) => {
2070 self.confirm_impl_candidate(obligation
, impl_def_id
)?
;
2071 Ok(VtableImpl(vtable_impl
))
2074 ClosureCandidate(closure_def_id
, substs
) => {
2075 let vtable_closure
=
2076 self.confirm_closure_candidate(obligation
, closure_def_id
, substs
)?
;
2077 Ok(VtableClosure(vtable_closure
))
2080 BuiltinObjectCandidate
=> {
2081 // This indicates something like `(Trait+Send) :
2082 // Send`. In this case, we know that this holds
2083 // because that's what the object type is telling us,
2084 // and there's really no additional obligations to
2085 // prove and no types in particular to unify etc.
2086 Ok(VtableParam(Vec
::new()))
2089 ObjectCandidate
=> {
2090 let data
= self.confirm_object_candidate(obligation
);
2091 Ok(VtableObject(data
))
2094 FnPointerCandidate
=> {
2096 self.confirm_fn_pointer_candidate(obligation
)?
;
2097 Ok(VtableFnPointer(fn_type
))
2100 ProjectionCandidate
=> {
2101 self.confirm_projection_candidate(obligation
);
2102 Ok(VtableParam(Vec
::new()))
2105 BuiltinUnsizeCandidate
=> {
2106 let data
= self.confirm_builtin_unsize_candidate(obligation
)?
;
2107 Ok(VtableBuiltin(data
))
2112 fn confirm_projection_candidate(&mut self,
2113 obligation
: &TraitObligation
<'tcx
>)
2115 let _
: Result
<(),()> =
2116 self.infcx
.commit_if_ok(|snapshot
| {
2118 self.match_projection_obligation_against_bounds_from_trait(obligation
,
2125 fn confirm_param_candidate(&mut self,
2126 obligation
: &TraitObligation
<'tcx
>,
2127 param
: ty
::PolyTraitRef
<'tcx
>)
2128 -> Vec
<PredicateObligation
<'tcx
>>
2130 debug
!("confirm_param_candidate({:?},{:?})",
2134 // During evaluation, we already checked that this
2135 // where-clause trait-ref could be unified with the obligation
2136 // trait-ref. Repeat that unification now without any
2137 // transactional boundary; it should not fail.
2138 match self.match_where_clause_trait_ref(obligation
, param
.clone()) {
2139 Ok(obligations
) => obligations
,
2141 bug
!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2148 fn confirm_builtin_candidate(&mut self,
2149 obligation
: &TraitObligation
<'tcx
>,
2150 bound
: ty
::BuiltinBound
)
2151 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2152 SelectionError
<'tcx
>>
2154 debug
!("confirm_builtin_candidate({:?})",
2157 match self.builtin_bound(bound
, obligation
)?
{
2158 If(nested
) => Ok(self.vtable_builtin_data(obligation
, bound
, nested
)),
2159 AmbiguousBuiltin
| ParameterBuiltin
=> {
2161 obligation
.cause
.span
,
2162 "builtin bound for {:?} was ambig",
2168 fn vtable_builtin_data(&mut self,
2169 obligation
: &TraitObligation
<'tcx
>,
2170 bound
: ty
::BuiltinBound
,
2171 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2172 -> VtableBuiltinData
<PredicateObligation
<'tcx
>>
2174 debug
!("vtable_builtin_data(obligation={:?}, bound={:?}, nested={:?})",
2175 obligation
, bound
, nested
);
2177 let trait_def
= match self.tcx().lang_items
.from_builtin_kind(bound
) {
2178 Ok(def_id
) => def_id
,
2180 bug
!("builtin trait definition not found");
2184 let obligations
= self.collect_predicates_for_types(obligation
, trait_def
, nested
);
2186 debug
!("vtable_builtin_data: obligations={:?}",
2189 VtableBuiltinData { nested: obligations }
2192 /// This handles the case where a `impl Foo for ..` impl is being used.
2193 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2195 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2196 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2197 fn confirm_default_impl_candidate(&mut self,
2198 obligation
: &TraitObligation
<'tcx
>,
2199 trait_def_id
: DefId
)
2200 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2202 debug
!("confirm_default_impl_candidate({:?}, {:?})",
2206 // binder is moved below
2207 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2208 let types
= self.constituent_types_for_ty(self_ty
);
2209 self.vtable_default_impl(obligation
, trait_def_id
, ty
::Binder(types
))
2212 fn confirm_default_impl_object_candidate(&mut self,
2213 obligation
: &TraitObligation
<'tcx
>,
2214 trait_def_id
: DefId
)
2215 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2217 debug
!("confirm_default_impl_object_candidate({:?}, {:?})",
2221 assert
!(self.tcx().has_attr(trait_def_id
, "rustc_reflect_like"));
2223 // OK to skip binder, it is reintroduced below
2224 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2226 ty
::TyTrait(ref data
) => {
2227 // OK to skip the binder, it is reintroduced below
2228 let input_types
= data
.principal
.skip_binder().substs
.types
.get_slice(TypeSpace
);
2229 let assoc_types
= data
.bounds
.projection_bounds
2231 .map(|pb
| pb
.skip_binder().ty
);
2232 let all_types
: Vec
<_
> = input_types
.iter().cloned()
2236 // reintroduce the two binding levels we skipped, then flatten into one
2237 let all_types
= ty
::Binder(ty
::Binder(all_types
));
2238 let all_types
= self.tcx().flatten_late_bound_regions(&all_types
);
2240 self.vtable_default_impl(obligation
, trait_def_id
, all_types
)
2243 bug
!("asked to confirm default object implementation for non-object type: {:?}",
2249 /// See `confirm_default_impl_candidate`
2250 fn vtable_default_impl(&mut self,
2251 obligation
: &TraitObligation
<'tcx
>,
2252 trait_def_id
: DefId
,
2253 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2254 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2256 debug
!("vtable_default_impl_data: nested={:?}", nested
);
2258 let mut obligations
= self.collect_predicates_for_types(obligation
,
2262 let trait_obligations
: Result
<Vec
<_
>,()> = self.infcx
.commit_if_ok(|snapshot
| {
2263 let poly_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
2264 let (trait_ref
, skol_map
) =
2265 self.infcx().skolemize_late_bound_regions(&poly_trait_ref
, snapshot
);
2266 Ok(self.impl_or_trait_obligations(obligation
.cause
.clone(),
2267 obligation
.recursion_depth
+ 1,
2274 // no Errors in that code above
2275 obligations
.append(&mut trait_obligations
.unwrap());
2277 debug
!("vtable_default_impl_data: obligations={:?}", obligations
);
2279 VtableDefaultImplData
{
2280 trait_def_id
: trait_def_id
,
2285 fn confirm_impl_candidate(&mut self,
2286 obligation
: &TraitObligation
<'tcx
>,
2288 -> Result
<VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>,
2289 SelectionError
<'tcx
>>
2291 debug
!("confirm_impl_candidate({:?},{:?})",
2295 // First, create the substitutions by matching the impl again,
2296 // this time not in a probe.
2297 self.infcx
.commit_if_ok(|snapshot
| {
2298 let (substs
, skol_map
) =
2299 self.rematch_impl(impl_def_id
, obligation
,
2301 debug
!("confirm_impl_candidate substs={:?}", substs
);
2302 Ok(self.vtable_impl(impl_def_id
, substs
, obligation
.cause
.clone(),
2303 obligation
.recursion_depth
+ 1, skol_map
, snapshot
))
2307 fn vtable_impl(&mut self,
2309 mut substs
: Normalized
<'tcx
, Substs
<'tcx
>>,
2310 cause
: ObligationCause
<'tcx
>,
2311 recursion_depth
: usize,
2312 skol_map
: infer
::SkolemizationMap
,
2313 snapshot
: &infer
::CombinedSnapshot
)
2314 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2316 debug
!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2322 let mut impl_obligations
=
2323 self.impl_or_trait_obligations(cause
,
2330 debug
!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2334 // Because of RFC447, the impl-trait-ref and obligations
2335 // are sufficient to determine the impl substs, without
2336 // relying on projections in the impl-trait-ref.
2338 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2339 impl_obligations
.append(&mut substs
.obligations
);
2341 VtableImplData
{ impl_def_id
: impl_def_id
,
2342 substs
: self.tcx().mk_substs(substs
.value
),
2343 nested
: impl_obligations
}
2346 fn confirm_object_candidate(&mut self,
2347 obligation
: &TraitObligation
<'tcx
>)
2348 -> VtableObjectData
<'tcx
>
2350 debug
!("confirm_object_candidate({:?})",
2353 // FIXME skipping binder here seems wrong -- we should
2354 // probably flatten the binder from the obligation and the
2355 // binder from the object. Have to try to make a broken test
2356 // case that results. -nmatsakis
2357 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2358 let poly_trait_ref
= match self_ty
.sty
{
2359 ty
::TyTrait(ref data
) => {
2360 data
.principal_trait_ref_with_self_ty(self.tcx(), self_ty
)
2363 span_bug
!(obligation
.cause
.span
,
2364 "object candidate with non-object");
2368 let mut upcast_trait_ref
= None
;
2372 // We want to find the first supertrait in the list of
2373 // supertraits that we can unify with, and do that
2374 // unification. We know that there is exactly one in the list
2375 // where we can unify because otherwise select would have
2376 // reported an ambiguity. (When we do find a match, also
2377 // record it for later.)
2379 util
::supertraits(self.tcx(), poly_trait_ref
)
2382 self.infcx
.commit_if_ok(
2383 |_
| self.match_poly_trait_ref(obligation
, t
))
2385 Ok(_
) => { upcast_trait_ref = Some(t); false }
2390 // Additionally, for each of the nonmatching predicates that
2391 // we pass over, we sum up the set of number of vtable
2392 // entries, so that we can compute the offset for the selected
2395 nonmatching
.map(|t
| util
::count_own_vtable_entries(self.tcx(), t
))
2401 upcast_trait_ref
: upcast_trait_ref
.unwrap(),
2402 vtable_base
: vtable_base
,
2406 fn confirm_fn_pointer_candidate(&mut self,
2407 obligation
: &TraitObligation
<'tcx
>)
2408 -> Result
<ty
::Ty
<'tcx
>,SelectionError
<'tcx
>>
2410 debug
!("confirm_fn_pointer_candidate({:?})",
2413 // ok to skip binder; it is reintroduced below
2414 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2415 let sig
= self_ty
.fn_sig();
2417 util
::closure_trait_ref_and_return_type(self.tcx(),
2418 obligation
.predicate
.def_id(),
2421 util
::TupleArgumentsFlag
::Yes
)
2422 .map_bound(|(trait_ref
, _
)| trait_ref
);
2424 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2425 obligation
.predicate
.to_poly_trait_ref(),
2430 fn confirm_closure_candidate(&mut self,
2431 obligation
: &TraitObligation
<'tcx
>,
2432 closure_def_id
: DefId
,
2433 substs
: &ty
::ClosureSubsts
<'tcx
>)
2434 -> Result
<VtableClosureData
<'tcx
, PredicateObligation
<'tcx
>>,
2435 SelectionError
<'tcx
>>
2437 debug
!("confirm_closure_candidate({:?},{:?},{:?})",
2445 } = self.closure_trait_ref(obligation
, closure_def_id
, substs
);
2447 debug
!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2452 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2453 obligation
.predicate
.to_poly_trait_ref(),
2456 Ok(VtableClosureData
{
2457 closure_def_id
: closure_def_id
,
2458 substs
: substs
.clone(),
2463 /// In the case of closure types and fn pointers,
2464 /// we currently treat the input type parameters on the trait as
2465 /// outputs. This means that when we have a match we have only
2466 /// considered the self type, so we have to go back and make sure
2467 /// to relate the argument types too. This is kind of wrong, but
2468 /// since we control the full set of impls, also not that wrong,
2469 /// and it DOES yield better error messages (since we don't report
2470 /// errors as if there is no applicable impl, but rather report
2471 /// errors are about mismatched argument types.
2473 /// Here is an example. Imagine we have a closure expression
2474 /// and we desugared it so that the type of the expression is
2475 /// `Closure`, and `Closure` expects an int as argument. Then it
2476 /// is "as if" the compiler generated this impl:
2478 /// impl Fn(int) for Closure { ... }
2480 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2481 /// we have matched the self-type `Closure`. At this point we'll
2482 /// compare the `int` to `usize` and generate an error.
2484 /// Note that this checking occurs *after* the impl has selected,
2485 /// because these output type parameters should not affect the
2486 /// selection of the impl. Therefore, if there is a mismatch, we
2487 /// report an error to the user.
2488 fn confirm_poly_trait_refs(&mut self,
2489 obligation_cause
: ObligationCause
,
2490 obligation_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2491 expected_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2492 -> Result
<(), SelectionError
<'tcx
>>
2494 let origin
= TypeOrigin
::RelateOutputImplTypes(obligation_cause
.span
);
2496 let obligation_trait_ref
= obligation_trait_ref
.clone();
2497 self.infcx
.sub_poly_trait_refs(false,
2499 expected_trait_ref
.clone(),
2500 obligation_trait_ref
.clone())
2501 // FIXME(#32730) propagate obligations
2502 .map(|InferOk { obligations, .. }
| assert
!(obligations
.is_empty()))
2503 .map_err(|e
| OutputTypeParameterMismatch(expected_trait_ref
, obligation_trait_ref
, e
))
2506 fn confirm_builtin_unsize_candidate(&mut self,
2507 obligation
: &TraitObligation
<'tcx
>,)
2508 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2509 SelectionError
<'tcx
>> {
2510 let tcx
= self.tcx();
2512 // assemble_candidates_for_unsizing should ensure there are no late bound
2513 // regions here. See the comment there for more details.
2514 let source
= self.infcx
.shallow_resolve(
2515 tcx
.no_late_bound_regions(&obligation
.self_ty()).unwrap());
2516 let target
= self.infcx
.shallow_resolve(obligation
.predicate
.0.input_types
()[0]);
2518 debug
!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2521 let mut nested
= vec
![];
2522 match (&source
.sty
, &target
.sty
) {
2523 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2524 (&ty
::TyTrait(ref data_a
), &ty
::TyTrait(ref data_b
)) => {
2525 // See assemble_candidates_for_unsizing for more info.
2526 let bounds
= ty
::ExistentialBounds
{
2527 region_bound
: data_b
.bounds
.region_bound
,
2528 builtin_bounds
: data_b
.bounds
.builtin_bounds
,
2529 projection_bounds
: data_a
.bounds
.projection_bounds
.clone(),
2532 let new_trait
= tcx
.mk_trait(data_a
.principal
.clone(), bounds
);
2533 let origin
= TypeOrigin
::Misc(obligation
.cause
.span
);
2534 let InferOk { obligations, .. }
=
2535 self.infcx
.sub_types(false, origin
, new_trait
, target
)
2536 .map_err(|_
| Unimplemented
)?
;
2537 // FIXME(#32730) propagate obligations
2538 assert
!(obligations
.is_empty());
2540 // Register one obligation for 'a: 'b.
2541 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2542 obligation
.cause
.body_id
,
2543 ObjectCastObligation(target
));
2544 let outlives
= ty
::OutlivesPredicate(data_a
.bounds
.region_bound
,
2545 data_b
.bounds
.region_bound
);
2546 nested
.push(Obligation
::with_depth(cause
,
2547 obligation
.recursion_depth
+ 1,
2548 ty
::Binder(outlives
).to_predicate()));
2552 (_
, &ty
::TyTrait(ref data
)) => {
2553 let object_did
= data
.principal_def_id();
2554 if !object_safety
::is_object_safe(tcx
, object_did
) {
2555 return Err(TraitNotObjectSafe(object_did
));
2558 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2559 obligation
.cause
.body_id
,
2560 ObjectCastObligation(target
));
2561 let mut push
= |predicate
| {
2562 nested
.push(Obligation
::with_depth(cause
.clone(),
2563 obligation
.recursion_depth
+ 1,
2567 // Create the obligation for casting from T to Trait.
2568 push(data
.principal_trait_ref_with_self_ty(tcx
, source
).to_predicate());
2570 // We can only make objects from sized types.
2571 let mut builtin_bounds
= data
.bounds
.builtin_bounds
;
2572 builtin_bounds
.insert(ty
::BoundSized
);
2574 // Create additional obligations for all the various builtin
2575 // bounds attached to the object cast. (In other words, if the
2576 // object type is Foo+Send, this would create an obligation
2577 // for the Send check.)
2578 for bound
in &builtin_bounds
{
2579 if let Ok(tr
) = util
::trait_ref_for_builtin_bound(tcx
, bound
, source
) {
2580 push(tr
.to_predicate());
2582 return Err(Unimplemented
);
2586 // Create obligations for the projection predicates.
2587 for bound
in data
.projection_bounds_with_self_ty(tcx
, source
) {
2588 push(bound
.to_predicate());
2591 // If the type is `Foo+'a`, ensures that the type
2592 // being cast to `Foo+'a` outlives `'a`:
2593 let outlives
= ty
::OutlivesPredicate(source
,
2594 data
.bounds
.region_bound
);
2595 push(ty
::Binder(outlives
).to_predicate());
2599 (&ty
::TyArray(a
, _
), &ty
::TySlice(b
)) => {
2600 let origin
= TypeOrigin
::Misc(obligation
.cause
.span
);
2601 let InferOk { obligations, .. }
=
2602 self.infcx
.sub_types(false, origin
, a
, b
)
2603 .map_err(|_
| Unimplemented
)?
;
2604 // FIXME(#32730) propagate obligations
2605 assert
!(obligations
.is_empty());
2608 // Struct<T> -> Struct<U>.
2609 (&ty
::TyStruct(def
, substs_a
), &ty
::TyStruct(_
, substs_b
)) => {
2612 .map(|f
| f
.unsubst_ty())
2613 .collect
::<Vec
<_
>>();
2615 // The last field of the structure has to exist and contain type parameters.
2616 let field
= if let Some(&field
) = fields
.last() {
2619 return Err(Unimplemented
);
2621 let mut ty_params
= vec
![];
2622 for ty
in field
.walk() {
2623 if let ty
::TyParam(p
) = ty
.sty
{
2624 assert
!(p
.space
== TypeSpace
);
2625 let idx
= p
.idx
as usize;
2626 if !ty_params
.contains(&idx
) {
2627 ty_params
.push(idx
);
2631 if ty_params
.is_empty() {
2632 return Err(Unimplemented
);
2635 // Replace type parameters used in unsizing with
2636 // TyError and ensure they do not affect any other fields.
2637 // This could be checked after type collection for any struct
2638 // with a potentially unsized trailing field.
2639 let mut new_substs
= substs_a
.clone();
2640 for &i
in &ty_params
{
2641 new_substs
.types
.get_mut_slice(TypeSpace
)[i
] = tcx
.types
.err
;
2643 for &ty
in fields
.split_last().unwrap().1 {
2644 if ty
.subst(tcx
, &new_substs
).references_error() {
2645 return Err(Unimplemented
);
2649 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2650 let inner_source
= field
.subst(tcx
, substs_a
);
2651 let inner_target
= field
.subst(tcx
, substs_b
);
2653 // Check that the source structure with the target's
2654 // type parameters is a subtype of the target.
2655 for &i
in &ty_params
{
2656 let param_b
= *substs_b
.types
.get(TypeSpace
, i
);
2657 new_substs
.types
.get_mut_slice(TypeSpace
)[i
] = param_b
;
2659 let new_struct
= tcx
.mk_struct(def
, tcx
.mk_substs(new_substs
));
2660 let origin
= TypeOrigin
::Misc(obligation
.cause
.span
);
2661 let InferOk { obligations, .. }
=
2662 self.infcx
.sub_types(false, origin
, new_struct
, target
)
2663 .map_err(|_
| Unimplemented
)?
;
2664 // FIXME(#32730) propagate obligations
2665 assert
!(obligations
.is_empty());
2667 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2668 nested
.push(util
::predicate_for_trait_def(tcx
,
2669 obligation
.cause
.clone(),
2670 obligation
.predicate
.def_id(),
2671 obligation
.recursion_depth
+ 1,
2673 vec
![inner_target
]));
2679 Ok(VtableBuiltinData { nested: nested }
)
2682 ///////////////////////////////////////////////////////////////////////////
2685 // Matching is a common path used for both evaluation and
2686 // confirmation. It basically unifies types that appear in impls
2687 // and traits. This does affect the surrounding environment;
2688 // therefore, when used during evaluation, match routines must be
2689 // run inside of a `probe()` so that their side-effects are
2692 fn rematch_impl(&mut self,
2694 obligation
: &TraitObligation
<'tcx
>,
2695 snapshot
: &infer
::CombinedSnapshot
)
2696 -> (Normalized
<'tcx
, Substs
<'tcx
>>, infer
::SkolemizationMap
)
2698 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
2699 Ok((substs
, skol_map
)) => (substs
, skol_map
),
2701 bug
!("Impl {:?} was matchable against {:?} but now is not",
2708 fn match_impl(&mut self,
2710 obligation
: &TraitObligation
<'tcx
>,
2711 snapshot
: &infer
::CombinedSnapshot
)
2712 -> Result
<(Normalized
<'tcx
, Substs
<'tcx
>>,
2713 infer
::SkolemizationMap
), ()>
2715 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2717 // Before we create the substitutions and everything, first
2718 // consider a "quick reject". This avoids creating more types
2719 // and so forth that we need to.
2720 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2724 let (skol_obligation
, skol_map
) = self.infcx().skolemize_late_bound_regions(
2725 &obligation
.predicate
,
2727 let skol_obligation_trait_ref
= skol_obligation
.trait_ref
;
2729 let impl_substs
= util
::fresh_type_vars_for_impl(self.infcx
,
2730 obligation
.cause
.span
,
2733 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(),
2736 let impl_trait_ref
=
2737 project
::normalize_with_depth(self,
2738 obligation
.cause
.clone(),
2739 obligation
.recursion_depth
+ 1,
2742 debug
!("match_impl(impl_def_id={:?}, obligation={:?}, \
2743 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2747 skol_obligation_trait_ref
);
2749 let origin
= TypeOrigin
::RelateOutputImplTypes(obligation
.cause
.span
);
2750 let InferOk { obligations, .. }
=
2751 self.infcx
.eq_trait_refs(false,
2753 impl_trait_ref
.value
.clone(),
2754 skol_obligation_trait_ref
)
2756 debug
!("match_impl: failed eq_trait_refs due to `{}`", e
);
2759 // FIXME(#32730) propagate obligations
2760 assert
!(obligations
.is_empty());
2762 if let Err(e
) = self.infcx
.leak_check(&skol_map
, snapshot
) {
2763 debug
!("match_impl: failed leak check due to `{}`", e
);
2767 debug
!("match_impl: success impl_substs={:?}", impl_substs
);
2770 obligations
: impl_trait_ref
.obligations
2774 fn fast_reject_trait_refs(&mut self,
2775 obligation
: &TraitObligation
,
2776 impl_trait_ref
: &ty
::TraitRef
)
2779 // We can avoid creating type variables and doing the full
2780 // substitution if we find that any of the input types, when
2781 // simplified, do not match.
2783 obligation
.predicate
.0.input_types
().iter()
2784 .zip(impl_trait_ref
.input_types())
2785 .any(|(&obligation_ty
, &impl_ty
)| {
2786 let simplified_obligation_ty
=
2787 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2788 let simplified_impl_ty
=
2789 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2791 simplified_obligation_ty
.is_some() &&
2792 simplified_impl_ty
.is_some() &&
2793 simplified_obligation_ty
!= simplified_impl_ty
2797 /// Normalize `where_clause_trait_ref` and try to match it against
2798 /// `obligation`. If successful, return any predicates that
2799 /// result from the normalization. Normalization is necessary
2800 /// because where-clauses are stored in the parameter environment
2802 fn match_where_clause_trait_ref(&mut self,
2803 obligation
: &TraitObligation
<'tcx
>,
2804 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2805 -> Result
<Vec
<PredicateObligation
<'tcx
>>,()>
2807 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)?
;
2811 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2812 /// obligation is satisfied.
2813 fn match_poly_trait_ref(&self,
2814 obligation
: &TraitObligation
<'tcx
>,
2815 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2818 debug
!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2822 let origin
= TypeOrigin
::RelateOutputImplTypes(obligation
.cause
.span
);
2823 self.infcx
.sub_poly_trait_refs(false,
2826 obligation
.predicate
.to_poly_trait_ref())
2827 // FIXME(#32730) propagate obligations
2828 .map(|InferOk { obligations, .. }
| assert
!(obligations
.is_empty()))
2832 ///////////////////////////////////////////////////////////////////////////
2835 fn match_fresh_trait_refs(&self,
2836 previous
: &ty
::PolyTraitRef
<'tcx
>,
2837 current
: &ty
::PolyTraitRef
<'tcx
>)
2840 let mut matcher
= ty
::_match
::Match
::new(self.tcx());
2841 matcher
.relate(previous
, current
).is_ok()
2844 fn push_stack
<'o
,'s
:'o
>(&mut self,
2845 previous_stack
: TraitObligationStackList
<'s
, 'tcx
>,
2846 obligation
: &'o TraitObligation
<'tcx
>)
2847 -> TraitObligationStack
<'o
, 'tcx
>
2849 let fresh_trait_ref
=
2850 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2852 TraitObligationStack
{
2853 obligation
: obligation
,
2854 fresh_trait_ref
: fresh_trait_ref
,
2855 previous
: previous_stack
,
2859 fn closure_trait_ref_unnormalized(&mut self,
2860 obligation
: &TraitObligation
<'tcx
>,
2861 closure_def_id
: DefId
,
2862 substs
: &ty
::ClosureSubsts
<'tcx
>)
2863 -> ty
::PolyTraitRef
<'tcx
>
2865 let closure_type
= self.infcx
.closure_type(closure_def_id
, substs
);
2866 let ty
::Binder((trait_ref
, _
)) =
2867 util
::closure_trait_ref_and_return_type(self.tcx(),
2868 obligation
.predicate
.def_id(),
2869 obligation
.predicate
.0.self_ty(), // (1)
2871 util
::TupleArgumentsFlag
::No
);
2872 // (1) Feels icky to skip the binder here, but OTOH we know
2873 // that the self-type is an unboxed closure type and hence is
2874 // in fact unparameterized (or at least does not reference any
2875 // regions bound in the obligation). Still probably some
2876 // refactoring could make this nicer.
2878 ty
::Binder(trait_ref
)
2881 fn closure_trait_ref(&mut self,
2882 obligation
: &TraitObligation
<'tcx
>,
2883 closure_def_id
: DefId
,
2884 substs
: &ty
::ClosureSubsts
<'tcx
>)
2885 -> Normalized
<'tcx
, ty
::PolyTraitRef
<'tcx
>>
2887 let trait_ref
= self.closure_trait_ref_unnormalized(
2888 obligation
, closure_def_id
, substs
);
2890 // A closure signature can contain associated types which
2891 // must be normalized.
2892 normalize_with_depth(self,
2893 obligation
.cause
.clone(),
2894 obligation
.recursion_depth
+1,
2898 /// Returns the obligations that are implied by instantiating an
2899 /// impl or trait. The obligations are substituted and fully
2900 /// normalized. This is used when confirming an impl or default
2902 fn impl_or_trait_obligations(&mut self,
2903 cause
: ObligationCause
<'tcx
>,
2904 recursion_depth
: usize,
2905 def_id
: DefId
, // of impl or trait
2906 substs
: &Substs
<'tcx
>, // for impl or trait
2907 skol_map
: infer
::SkolemizationMap
,
2908 snapshot
: &infer
::CombinedSnapshot
)
2909 -> Vec
<PredicateObligation
<'tcx
>>
2911 debug
!("impl_or_trait_obligations(def_id={:?})", def_id
);
2912 let tcx
= self.tcx();
2914 // To allow for one-pass evaluation of the nested obligation,
2915 // each predicate must be preceded by the obligations required
2917 // for example, if we have:
2918 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2919 // the impl will have the following predicates:
2920 // <V as Iterator>::Item = U,
2921 // U: Iterator, U: Sized,
2922 // V: Iterator, V: Sized,
2923 // <U as Iterator>::Item: Copy
2924 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2925 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2926 // `$1: Copy`, so we must ensure the obligations are emitted in
2928 let predicates
= tcx
2929 .lookup_predicates(def_id
)
2931 .flat_map(|predicate
| {
2933 normalize_with_depth(self, cause
.clone(), recursion_depth
,
2934 &predicate
.subst(tcx
, substs
));
2935 predicate
.obligations
.into_iter().chain(
2937 cause
: cause
.clone(),
2938 recursion_depth
: recursion_depth
,
2939 predicate
: predicate
.value
2942 self.infcx().plug_leaks(skol_map
, snapshot
, &predicates
)
2945 #[allow(unused_comparisons)]
2946 fn derived_cause(&self,
2947 obligation
: &TraitObligation
<'tcx
>,
2948 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>)
2949 -> ObligationCause
<'tcx
>
2952 * Creates a cause for obligations that are derived from
2953 * `obligation` by a recursive search (e.g., for a builtin
2954 * bound, or eventually a `impl Foo for ..`). If `obligation`
2955 * is itself a derived obligation, this is just a clone, but
2956 * otherwise we create a "derived obligation" cause so as to
2957 * keep track of the original root obligation for error
2961 // NOTE(flaper87): As of now, it keeps track of the whole error
2962 // chain. Ideally, we should have a way to configure this either
2963 // by using -Z verbose or just a CLI argument.
2964 if obligation
.recursion_depth
>= 0 {
2965 let derived_cause
= DerivedObligationCause
{
2966 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2967 parent_code
: Rc
::new(obligation
.cause
.code
.clone())
2969 let derived_code
= variant(derived_cause
);
2970 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2972 obligation
.cause
.clone()
2977 impl<'tcx
> SelectionCache
<'tcx
> {
2978 pub fn new() -> SelectionCache
<'tcx
> {
2980 hashmap
: RefCell
::new(FnvHashMap())
2985 impl<'tcx
> EvaluationCache
<'tcx
> {
2986 pub fn new() -> EvaluationCache
<'tcx
> {
2988 hashmap
: RefCell
::new(FnvHashMap())
2993 impl<'o
,'tcx
> TraitObligationStack
<'o
,'tcx
> {
2994 fn list(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2995 TraitObligationStackList
::with(self)
2998 fn iter(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
3003 #[derive(Copy, Clone)]
3004 struct TraitObligationStackList
<'o
,'tcx
:'o
> {
3005 head
: Option
<&'o TraitObligationStack
<'o
,'tcx
>>
3008 impl<'o
,'tcx
> TraitObligationStackList
<'o
,'tcx
> {
3009 fn empty() -> TraitObligationStackList
<'o
,'tcx
> {
3010 TraitObligationStackList { head: None }
3013 fn with(r
: &'o TraitObligationStack
<'o
,'tcx
>) -> TraitObligationStackList
<'o
,'tcx
> {
3014 TraitObligationStackList { head: Some(r) }
3018 impl<'o
,'tcx
> Iterator
for TraitObligationStackList
<'o
,'tcx
>{
3019 type Item
= &'o TraitObligationStack
<'o
,'tcx
>;
3021 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
,'tcx
>> {
3032 impl<'o
,'tcx
> fmt
::Debug
for TraitObligationStack
<'o
,'tcx
> {
3033 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
3034 write
!(f
, "TraitObligationStack({:?})", self.obligation
)
3038 impl EvaluationResult
{
3039 fn may_apply(&self) -> bool
{
3043 EvaluatedToUnknown
=> true,
3045 EvaluatedToErr
=> false
3050 impl MethodMatchResult
{
3051 pub fn may_apply(&self) -> bool
{
3053 MethodMatched(_
) => true,
3054 MethodAmbiguous(_
) => true,
3055 MethodDidNotMatch
=> false,