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::EvaluationResult
::*;
19 use super::DerivedObligationCause
;
21 use super::project
::{normalize_with_depth, Normalized}
;
22 use super::{PredicateObligation, TraitObligation, ObligationCause}
;
23 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation}
;
24 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch}
;
25 use super::{ObjectCastObligation, Obligation}
;
27 use super::TraitNotObjectSafe
;
29 use super::SelectionResult
;
30 use super::{VtableBuiltin
, VtableImpl
, VtableParam
, VtableClosure
,
31 VtableFnPointer
, VtableObject
, VtableDefaultImpl
};
32 use super::{VtableImplData
, VtableObjectData
, VtableBuiltinData
,
33 VtableClosureData
, VtableDefaultImplData
, VtableFnPointerData
};
36 use hir
::def_id
::DefId
;
38 use infer
::{InferCtxt, InferOk, TypeFreshener}
;
39 use ty
::subst
::{Kind, Subst, Substs}
;
40 use ty
::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable}
;
43 use ty
::relate
::TypeRelation
;
44 use middle
::lang_items
;
46 use rustc_data_structures
::bitvec
::BitVector
;
47 use rustc_data_structures
::snapshot_vec
::{SnapshotVecDelegate, SnapshotVec}
;
48 use std
::cell
::RefCell
;
50 use std
::marker
::PhantomData
;
55 use util
::nodemap
::FxHashMap
;
57 struct InferredObligationsSnapshotVecDelegate
<'tcx
> {
58 phantom
: PhantomData
<&'tcx
i32>,
60 impl<'tcx
> SnapshotVecDelegate
for InferredObligationsSnapshotVecDelegate
<'tcx
> {
61 type Value
= PredicateObligation
<'tcx
>;
63 fn reverse(_
: &mut Vec
<Self::Value
>, _
: Self::Undo
) {}
66 pub struct SelectionContext
<'cx
, 'gcx
: 'cx
+'tcx
, 'tcx
: 'cx
> {
67 infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>,
69 /// Freshener used specifically for skolemizing entries on the
70 /// obligation stack. This ensures that all entries on the stack
71 /// at one time will have the same set of skolemized entries,
72 /// which is important for checking for trait bounds that
73 /// recursively require themselves.
74 freshener
: TypeFreshener
<'cx
, 'gcx
, 'tcx
>,
76 /// If true, indicates that the evaluation should be conservative
77 /// and consider the possibility of types outside this crate.
78 /// This comes up primarily when resolving ambiguity. Imagine
79 /// there is some trait reference `$0 : Bar` where `$0` is an
80 /// inference variable. If `intercrate` is true, then we can never
81 /// say for sure that this reference is not implemented, even if
82 /// there are *no impls at all for `Bar`*, because `$0` could be
83 /// bound to some type that in a downstream crate that implements
84 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
85 /// though, we set this to false, because we are only interested
86 /// in types that the user could actually have written --- in
87 /// other words, we consider `$0 : Bar` to be unimplemented if
88 /// there is no type that the user could *actually name* that
89 /// would satisfy it. This avoids crippling inference, basically.
92 inferred_obligations
: SnapshotVec
<InferredObligationsSnapshotVecDelegate
<'tcx
>>,
95 // A stack that walks back up the stack frame.
96 struct TraitObligationStack
<'prev
, 'tcx
: 'prev
> {
97 obligation
: &'prev TraitObligation
<'tcx
>,
99 /// Trait ref from `obligation` but skolemized with the
100 /// selection-context's freshener. Used to check for recursion.
101 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
103 previous
: TraitObligationStackList
<'prev
, 'tcx
>,
107 pub struct SelectionCache
<'tcx
> {
108 hashmap
: RefCell
<FxHashMap
<ty
::TraitRef
<'tcx
>,
109 SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>>,
112 pub enum MethodMatchResult
{
113 MethodMatched(MethodMatchedData
),
114 MethodAmbiguous(/* list of impls that could apply */ Vec
<DefId
>),
118 #[derive(Copy, Clone, Debug)]
119 pub enum MethodMatchedData
{
120 // In the case of a precise match, we don't really need to store
121 // how the match was found. So don't.
124 // In the case of a coercion, we need to know the precise impl so
125 // that we can determine the type to which things were coerced.
126 CoerciveMethodMatch(/* impl we matched */ DefId
)
129 /// The selection process begins by considering all impls, where
130 /// clauses, and so forth that might resolve an obligation. Sometimes
131 /// we'll be able to say definitively that (e.g.) an impl does not
132 /// apply to the obligation: perhaps it is defined for `usize` but the
133 /// obligation is for `int`. In that case, we drop the impl out of the
134 /// list. But the other cases are considered *candidates*.
136 /// For selection to succeed, there must be exactly one matching
137 /// candidate. If the obligation is fully known, this is guaranteed
138 /// by coherence. However, if the obligation contains type parameters
139 /// or variables, there may be multiple such impls.
141 /// It is not a real problem if multiple matching impls exist because
142 /// of type variables - it just means the obligation isn't sufficiently
143 /// elaborated. In that case we report an ambiguity, and the caller can
144 /// try again after more type information has been gathered or report a
145 /// "type annotations required" error.
147 /// However, with type parameters, this can be a real problem - type
148 /// parameters don't unify with regular types, but they *can* unify
149 /// with variables from blanket impls, and (unless we know its bounds
150 /// will always be satisfied) picking the blanket impl will be wrong
151 /// for at least *some* substitutions. To make this concrete, if we have
153 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
154 /// impl<T: fmt::Debug> AsDebug for T {
156 /// fn debug(self) -> fmt::Debug { self }
158 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
160 /// we can't just use the impl to resolve the <T as AsDebug> obligation
161 /// - a type from another crate (that doesn't implement fmt::Debug) could
162 /// implement AsDebug.
164 /// Because where-clauses match the type exactly, multiple clauses can
165 /// only match if there are unresolved variables, and we can mostly just
166 /// report this ambiguity in that case. This is still a problem - we can't
167 /// *do anything* with ambiguities that involve only regions. This is issue
170 /// If a single where-clause matches and there are no inference
171 /// variables left, then it definitely matches and we can just select
174 /// In fact, we even select the where-clause when the obligation contains
175 /// inference variables. The can lead to inference making "leaps of logic",
176 /// for example in this situation:
178 /// pub trait Foo<T> { fn foo(&self) -> T; }
179 /// impl<T> Foo<()> for T { fn foo(&self) { } }
180 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
182 /// pub fn foo<T>(t: T) where T: Foo<bool> {
183 /// println!("{:?}", <T as Foo<_>>::foo(&t));
185 /// fn main() { foo(false); }
187 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
188 /// impl and the where-clause. We select the where-clause and unify $0=bool,
189 /// so the program prints "false". However, if the where-clause is omitted,
190 /// the blanket impl is selected, we unify $0=(), and the program prints
193 /// Exactly the same issues apply to projection and object candidates, except
194 /// that we can have both a projection candidate and a where-clause candidate
195 /// for the same obligation. In that case either would do (except that
196 /// different "leaps of logic" would occur if inference variables are
197 /// present), and we just pick the where-clause. This is, for example,
198 /// required for associated types to work in default impls, as the bounds
199 /// are visible both as projection bounds and as where-clauses from the
200 /// parameter environment.
201 #[derive(PartialEq,Eq,Debug,Clone)]
202 enum SelectionCandidate
<'tcx
> {
203 BuiltinCandidate { has_nested: bool }
,
204 ParamCandidate(ty
::PolyTraitRef
<'tcx
>),
205 ImplCandidate(DefId
),
206 DefaultImplCandidate(DefId
),
207 DefaultImplObjectCandidate(DefId
),
209 /// This is a trait matching with a projected type as `Self`, and
210 /// we found an applicable bound in the trait definition.
213 /// Implementation of a `Fn`-family trait by one of the anonymous types
214 /// generated for a `||` expression. The ty::ClosureKind informs the
215 /// confirmation step what ClosureKind obligation to emit.
216 ClosureCandidate(/* closure */ DefId
, ty
::ClosureSubsts
<'tcx
>, ty
::ClosureKind
),
218 /// Implementation of a `Fn`-family trait by one of the anonymous
219 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
224 BuiltinObjectCandidate
,
226 BuiltinUnsizeCandidate
,
229 impl<'a
, 'tcx
> ty
::Lift
<'tcx
> for SelectionCandidate
<'a
> {
230 type Lifted
= SelectionCandidate
<'tcx
>;
231 fn lift_to_tcx
<'b
, 'gcx
>(&self, tcx
: TyCtxt
<'b
, 'gcx
, 'tcx
>) -> Option
<Self::Lifted
> {
233 BuiltinCandidate { has_nested }
=> {
235 has_nested
: has_nested
238 ImplCandidate(def_id
) => ImplCandidate(def_id
),
239 DefaultImplCandidate(def_id
) => DefaultImplCandidate(def_id
),
240 DefaultImplObjectCandidate(def_id
) => {
241 DefaultImplObjectCandidate(def_id
)
243 ProjectionCandidate
=> ProjectionCandidate
,
244 FnPointerCandidate
=> FnPointerCandidate
,
245 ObjectCandidate
=> ObjectCandidate
,
246 BuiltinObjectCandidate
=> BuiltinObjectCandidate
,
247 BuiltinUnsizeCandidate
=> BuiltinUnsizeCandidate
,
249 ParamCandidate(ref trait_ref
) => {
250 return tcx
.lift(trait_ref
).map(ParamCandidate
);
252 ClosureCandidate(def_id
, ref substs
, kind
) => {
253 return tcx
.lift(substs
).map(|substs
| {
254 ClosureCandidate(def_id
, substs
, kind
)
261 struct SelectionCandidateSet
<'tcx
> {
262 // a list of candidates that definitely apply to the current
263 // obligation (meaning: types unify).
264 vec
: Vec
<SelectionCandidate
<'tcx
>>,
266 // if this is true, then there were candidates that might or might
267 // not have applied, but we couldn't tell. This occurs when some
268 // of the input types are type variables, in which case there are
269 // various "builtin" rules that might or might not trigger.
273 #[derive(PartialEq,Eq,Debug,Clone)]
274 struct EvaluatedCandidate
<'tcx
> {
275 candidate
: SelectionCandidate
<'tcx
>,
276 evaluation
: EvaluationResult
,
279 /// When does the builtin impl for `T: Trait` apply?
280 enum BuiltinImplConditions
<'tcx
> {
281 /// The impl is conditional on T1,T2,.. : Trait
282 Where(ty
::Binder
<Vec
<Ty
<'tcx
>>>),
283 /// There is no built-in impl. There may be some other
284 /// candidate (a where-clause or user-defined impl).
286 /// There is *no* impl for this, builtin or not. Ignore
287 /// all where-clauses.
289 /// It is unknown whether there is an impl.
293 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
294 /// The result of trait evaluation. The order is important
295 /// here as the evaluation of a list is the maximum of the
297 enum EvaluationResult
{
298 /// Evaluation successful
300 /// Evaluation failed because of recursion - treated as ambiguous
302 /// Evaluation is known to be ambiguous
304 /// Evaluation failed
309 pub struct EvaluationCache
<'tcx
> {
310 hashmap
: RefCell
<FxHashMap
<ty
::PolyTraitRef
<'tcx
>, EvaluationResult
>>
313 impl<'cx
, 'gcx
, 'tcx
> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
314 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>) -> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
317 freshener
: infcx
.freshener(),
319 inferred_obligations
: SnapshotVec
::new(),
323 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>) -> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
326 freshener
: infcx
.freshener(),
328 inferred_obligations
: SnapshotVec
::new(),
332 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
> {
336 pub fn tcx(&self) -> TyCtxt
<'cx
, 'gcx
, 'tcx
> {
340 pub fn param_env(&self) -> &'cx ty
::ParameterEnvironment
<'gcx
> {
341 self.infcx
.param_env()
344 pub fn closure_typer(&self) -> &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
> {
348 pub fn projection_mode(&self) -> Reveal
{
349 self.infcx
.projection_mode()
352 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
354 fn in_snapshot
<R
, F
>(&mut self, f
: F
) -> R
355 where F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> R
357 // The irrefutable nature of the operation means we don't need to snapshot the
358 // inferred_obligations vector.
359 self.infcx
.in_snapshot(|snapshot
| f(self, snapshot
))
362 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
364 fn probe
<R
, F
>(&mut self, f
: F
) -> R
365 where F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> R
367 let inferred_obligations_snapshot
= self.inferred_obligations
.start_snapshot();
368 let result
= self.infcx
.probe(|snapshot
| f(self, snapshot
));
369 self.inferred_obligations
.rollback_to(inferred_obligations_snapshot
);
373 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
374 /// the transaction fails and s.t. old obligations are retained.
375 fn commit_if_ok
<T
, E
, F
>(&mut self, f
: F
) -> Result
<T
, E
> where
376 F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> Result
<T
, E
>
378 let inferred_obligations_snapshot
= self.inferred_obligations
.start_snapshot();
379 match self.infcx
.commit_if_ok(|snapshot
| f(self, snapshot
)) {
381 self.inferred_obligations
.commit(inferred_obligations_snapshot
);
385 self.inferred_obligations
.rollback_to(inferred_obligations_snapshot
);
392 ///////////////////////////////////////////////////////////////////////////
395 // The selection phase tries to identify *how* an obligation will
396 // be resolved. For example, it will identify which impl or
397 // parameter bound is to be used. The process can be inconclusive
398 // if the self type in the obligation is not fully inferred. Selection
399 // can result in an error in one of two ways:
401 // 1. If no applicable impl or parameter bound can be found.
402 // 2. If the output type parameters in the obligation do not match
403 // those specified by the impl/bound. For example, if the obligation
404 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
405 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
407 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
408 /// type environment by performing unification.
409 pub fn select(&mut self, obligation
: &TraitObligation
<'tcx
>)
410 -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
411 debug
!("select({:?})", obligation
);
412 assert
!(!obligation
.predicate
.has_escaping_regions());
414 let dep_node
= obligation
.predicate
.dep_node();
415 let _task
= self.tcx().dep_graph
.in_task(dep_node
);
417 let stack
= self.push_stack(TraitObligationStackList
::empty(), obligation
);
418 match self.candidate_from_obligation(&stack
)?
{
421 let mut candidate
= self.confirm_candidate(obligation
, candidate
)?
;
422 let inferred_obligations
= (*self.inferred_obligations
).into_iter().cloned();
423 candidate
.nested_obligations_mut().extend(inferred_obligations
);
429 ///////////////////////////////////////////////////////////////////////////
432 // Tests whether an obligation can be selected or whether an impl
433 // can be applied to particular types. It skips the "confirmation"
434 // step and hence completely ignores output type parameters.
436 // The result is "true" if the obligation *may* hold and "false" if
437 // we can be sure it does not.
439 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
440 pub fn evaluate_obligation(&mut self,
441 obligation
: &PredicateObligation
<'tcx
>)
444 debug
!("evaluate_obligation({:?})",
447 self.probe(|this
, _
| {
448 this
.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
453 /// Evaluates whether the obligation `obligation` can be satisfied,
454 /// and returns `false` if not certain. However, this is not entirely
455 /// accurate if inference variables are involved.
456 pub fn evaluate_obligation_conservatively(&mut self,
457 obligation
: &PredicateObligation
<'tcx
>)
460 debug
!("evaluate_obligation_conservatively({:?})",
463 self.probe(|this
, _
| {
464 this
.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
469 /// Evaluates the predicates in `predicates` recursively. Note that
470 /// this applies projections in the predicates, and therefore
471 /// is run within an inference probe.
472 fn evaluate_predicates_recursively
<'a
,'o
,I
>(&mut self,
473 stack
: TraitObligationStackList
<'o
, 'tcx
>,
476 where I
: Iterator
<Item
=&'a PredicateObligation
<'tcx
>>, 'tcx
:'a
478 let mut result
= EvaluatedToOk
;
479 for obligation
in predicates
{
480 let eval
= self.evaluate_predicate_recursively(stack
, obligation
);
481 debug
!("evaluate_predicate_recursively({:?}) = {:?}",
484 EvaluatedToErr
=> { return EvaluatedToErr; }
485 EvaluatedToAmbig
=> { result = EvaluatedToAmbig; }
486 EvaluatedToUnknown
=> {
487 if result
< EvaluatedToUnknown
{
488 result
= EvaluatedToUnknown
;
497 fn evaluate_predicate_recursively
<'o
>(&mut self,
498 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
499 obligation
: &PredicateObligation
<'tcx
>)
502 debug
!("evaluate_predicate_recursively({:?})",
505 // Check the cache from the tcx of predicates that we know
506 // have been proven elsewhere. This cache only contains
507 // predicates that are global in scope and hence unaffected by
508 // the current environment.
509 if self.tcx().fulfilled_predicates
.borrow().check_duplicate(&obligation
.predicate
) {
510 return EvaluatedToOk
;
513 match obligation
.predicate
{
514 ty
::Predicate
::Trait(ref t
) => {
515 assert
!(!t
.has_escaping_regions());
516 let obligation
= obligation
.with(t
.clone());
517 self.evaluate_obligation_recursively(previous_stack
, &obligation
)
520 ty
::Predicate
::Equate(ref p
) => {
521 // does this code ever run?
522 match self.infcx
.equality_predicate(&obligation
.cause
, p
) {
523 Ok(InferOk { obligations, .. }
) => {
524 self.inferred_obligations
.extend(obligations
);
527 Err(_
) => EvaluatedToErr
531 ty
::Predicate
::WellFormed(ty
) => {
532 match ty
::wf
::obligations(self.infcx
, obligation
.cause
.body_id
,
533 ty
, obligation
.cause
.span
) {
535 self.evaluate_predicates_recursively(previous_stack
, obligations
.iter()),
541 ty
::Predicate
::TypeOutlives(..) | ty
::Predicate
::RegionOutlives(..) => {
542 // we do not consider region relationships when
543 // evaluating trait matches
547 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
548 if self.tcx().is_object_safe(trait_def_id
) {
555 ty
::Predicate
::Projection(ref data
) => {
556 let project_obligation
= obligation
.with(data
.clone());
557 match project
::poly_project_and_unify_type(self, &project_obligation
) {
558 Ok(Some(subobligations
)) => {
559 self.evaluate_predicates_recursively(previous_stack
,
560 subobligations
.iter())
571 ty
::Predicate
::ClosureKind(closure_def_id
, kind
) => {
572 match self.infcx
.closure_kind(closure_def_id
) {
573 Some(closure_kind
) => {
574 if closure_kind
.extends(kind
) {
588 fn evaluate_obligation_recursively
<'o
>(&mut self,
589 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
590 obligation
: &TraitObligation
<'tcx
>)
593 debug
!("evaluate_obligation_recursively({:?})",
596 let stack
= self.push_stack(previous_stack
, obligation
);
597 let fresh_trait_ref
= stack
.fresh_trait_ref
;
598 if let Some(result
) = self.check_evaluation_cache(fresh_trait_ref
) {
599 debug
!("CACHE HIT: EVAL({:?})={:?}",
605 let result
= self.evaluate_stack(&stack
);
607 debug
!("CACHE MISS: EVAL({:?})={:?}",
610 self.insert_evaluation_cache(fresh_trait_ref
, result
);
615 fn evaluate_stack
<'o
>(&mut self,
616 stack
: &TraitObligationStack
<'o
, 'tcx
>)
619 // In intercrate mode, whenever any of the types are unbound,
620 // there can always be an impl. Even if there are no impls in
621 // this crate, perhaps the type would be unified with
622 // something from another crate that does provide an impl.
624 // In intra mode, we must still be conservative. The reason is
625 // that we want to avoid cycles. Imagine an impl like:
627 // impl<T:Eq> Eq for Vec<T>
629 // and a trait reference like `$0 : Eq` where `$0` is an
630 // unbound variable. When we evaluate this trait-reference, we
631 // will unify `$0` with `Vec<$1>` (for some fresh variable
632 // `$1`), on the condition that `$1 : Eq`. We will then wind
633 // up with many candidates (since that are other `Eq` impls
634 // that apply) and try to winnow things down. This results in
635 // a recursive evaluation that `$1 : Eq` -- as you can
636 // imagine, this is just where we started. To avoid that, we
637 // check for unbound variables and return an ambiguous (hence possible)
638 // match if we've seen this trait before.
640 // This suffices to allow chains like `FnMut` implemented in
641 // terms of `Fn` etc, but we could probably make this more
643 let unbound_input_types
= stack
.fresh_trait_ref
.input_types().any(|ty
| ty
.is_fresh());
644 if unbound_input_types
&& self.intercrate
{
645 debug
!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
646 stack
.fresh_trait_ref
);
647 return EvaluatedToAmbig
;
649 if unbound_input_types
&&
650 stack
.iter().skip(1).any(
651 |prev
| self.match_fresh_trait_refs(&stack
.fresh_trait_ref
,
652 &prev
.fresh_trait_ref
))
654 debug
!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
655 stack
.fresh_trait_ref
);
656 return EvaluatedToUnknown
;
659 // If there is any previous entry on the stack that precisely
660 // matches this obligation, then we can assume that the
661 // obligation is satisfied for now (still all other conditions
662 // must be met of course). One obvious case this comes up is
663 // marker traits like `Send`. Think of a linked list:
665 // struct List<T> { data: T, next: Option<Box<List<T>>> {
667 // `Box<List<T>>` will be `Send` if `T` is `Send` and
668 // `Option<Box<List<T>>>` is `Send`, and in turn
669 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
672 // Note that we do this comparison using the `fresh_trait_ref`
673 // fields. Because these have all been skolemized using
674 // `self.freshener`, we can be sure that (a) this will not
675 // affect the inferencer state and (b) that if we see two
676 // skolemized types with the same index, they refer to the
677 // same unbound type variable.
680 .skip(1) // skip top-most frame
681 .any(|prev
| stack
.fresh_trait_ref
== prev
.fresh_trait_ref
)
683 debug
!("evaluate_stack({:?}) --> recursive",
684 stack
.fresh_trait_ref
);
685 return EvaluatedToOk
;
688 match self.candidate_from_obligation(stack
) {
689 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
690 Ok(None
) => EvaluatedToAmbig
,
691 Err(..) => EvaluatedToErr
695 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
696 /// obligations are met. Returns true if `candidate` remains viable after this further
698 fn evaluate_candidate
<'o
>(&mut self,
699 stack
: &TraitObligationStack
<'o
, 'tcx
>,
700 candidate
: &SelectionCandidate
<'tcx
>)
703 debug
!("evaluate_candidate: depth={} candidate={:?}",
704 stack
.obligation
.recursion_depth
, candidate
);
705 let result
= self.probe(|this
, _
| {
706 let candidate
= (*candidate
).clone();
707 match this
.confirm_candidate(stack
.obligation
, candidate
) {
709 this
.evaluate_predicates_recursively(
711 selection
.nested_obligations().iter())
713 Err(..) => EvaluatedToErr
716 debug
!("evaluate_candidate: depth={} result={:?}",
717 stack
.obligation
.recursion_depth
, result
);
721 fn check_evaluation_cache(&self, trait_ref
: ty
::PolyTraitRef
<'tcx
>)
722 -> Option
<EvaluationResult
>
724 if self.can_use_global_caches() {
725 let cache
= self.tcx().evaluation_cache
.hashmap
.borrow();
726 if let Some(cached
) = cache
.get(&trait_ref
) {
727 return Some(cached
.clone());
730 self.infcx
.evaluation_cache
.hashmap
.borrow().get(&trait_ref
).cloned()
733 fn insert_evaluation_cache(&mut self,
734 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
735 result
: EvaluationResult
)
737 // Avoid caching results that depend on more than just the trait-ref:
738 // The stack can create EvaluatedToUnknown, and closure signatures
739 // being yet uninferred can create "spurious" EvaluatedToAmbig
740 // and EvaluatedToOk.
741 if result
== EvaluatedToUnknown
||
742 ((result
== EvaluatedToAmbig
|| result
== EvaluatedToOk
)
743 && trait_ref
.has_closure_types())
748 if self.can_use_global_caches() {
749 let mut cache
= self.tcx().evaluation_cache
.hashmap
.borrow_mut();
750 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
751 cache
.insert(trait_ref
, result
);
756 self.infcx
.evaluation_cache
.hashmap
.borrow_mut().insert(trait_ref
, result
);
759 ///////////////////////////////////////////////////////////////////////////
760 // CANDIDATE ASSEMBLY
762 // The selection process begins by examining all in-scope impls,
763 // caller obligations, and so forth and assembling a list of
764 // candidates. See `README.md` and the `Candidate` type for more
767 fn candidate_from_obligation
<'o
>(&mut self,
768 stack
: &TraitObligationStack
<'o
, 'tcx
>)
769 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
771 // Watch out for overflow. This intentionally bypasses (and does
772 // not update) the cache.
773 let recursion_limit
= self.infcx
.tcx
.sess
.recursion_limit
.get();
774 if stack
.obligation
.recursion_depth
>= recursion_limit
{
775 self.infcx().report_overflow_error(&stack
.obligation
, true);
778 // Check the cache. Note that we skolemize the trait-ref
779 // separately rather than using `stack.fresh_trait_ref` -- this
780 // is because we want the unbound variables to be replaced
781 // with fresh skolemized types starting from index 0.
782 let cache_fresh_trait_pred
=
783 self.infcx
.freshen(stack
.obligation
.predicate
.clone());
784 debug
!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
785 cache_fresh_trait_pred
,
787 assert
!(!stack
.obligation
.predicate
.has_escaping_regions());
789 if let Some(c
) = self.check_candidate_cache(&cache_fresh_trait_pred
) {
790 debug
!("CACHE HIT: SELECT({:?})={:?}",
791 cache_fresh_trait_pred
,
796 // If no match, compute result and insert into cache.
797 let candidate
= self.candidate_from_obligation_no_cache(stack
);
799 if self.should_update_candidate_cache(&cache_fresh_trait_pred
, &candidate
) {
800 debug
!("CACHE MISS: SELECT({:?})={:?}",
801 cache_fresh_trait_pred
, candidate
);
802 self.insert_candidate_cache(cache_fresh_trait_pred
, candidate
.clone());
808 // Treat negative impls as unimplemented
809 fn filter_negative_impls(&self, candidate
: SelectionCandidate
<'tcx
>)
810 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
811 if let ImplCandidate(def_id
) = candidate
{
812 if self.tcx().trait_impl_polarity(def_id
) == hir
::ImplPolarity
::Negative
{
813 return Err(Unimplemented
)
819 fn candidate_from_obligation_no_cache
<'o
>(&mut self,
820 stack
: &TraitObligationStack
<'o
, 'tcx
>)
821 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
823 if stack
.obligation
.predicate
.references_error() {
824 // If we encounter a `TyError`, we generally prefer the
825 // most "optimistic" result in response -- that is, the
826 // one least likely to report downstream errors. But
827 // because this routine is shared by coherence and by
828 // trait selection, there isn't an obvious "right" choice
829 // here in that respect, so we opt to just return
830 // ambiguity and let the upstream clients sort it out.
834 if !self.is_knowable(stack
) {
835 debug
!("coherence stage: not knowable");
839 let candidate_set
= self.assemble_candidates(stack
)?
;
841 if candidate_set
.ambiguous
{
842 debug
!("candidate set contains ambig");
846 let mut candidates
= candidate_set
.vec
;
848 debug
!("assembled {} candidates for {:?}: {:?}",
853 // At this point, we know that each of the entries in the
854 // candidate set is *individually* applicable. Now we have to
855 // figure out if they contain mutual incompatibilities. This
856 // frequently arises if we have an unconstrained input type --
857 // for example, we are looking for $0:Eq where $0 is some
858 // unconstrained type variable. In that case, we'll get a
859 // candidate which assumes $0 == int, one that assumes $0 ==
860 // usize, etc. This spells an ambiguity.
862 // If there is more than one candidate, first winnow them down
863 // by considering extra conditions (nested obligations and so
864 // forth). We don't winnow if there is exactly one
865 // candidate. This is a relatively minor distinction but it
866 // can lead to better inference and error-reporting. An
867 // example would be if there was an impl:
869 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
871 // and we were to see some code `foo.push_clone()` where `boo`
872 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
873 // we were to winnow, we'd wind up with zero candidates.
874 // Instead, we select the right impl now but report `Bar does
875 // not implement Clone`.
876 if candidates
.len() == 1 {
877 return self.filter_negative_impls(candidates
.pop().unwrap());
880 // Winnow, but record the exact outcome of evaluation, which
881 // is needed for specialization.
882 let mut candidates
: Vec
<_
> = candidates
.into_iter().filter_map(|c
| {
883 let eval
= self.evaluate_candidate(stack
, &c
);
884 if eval
.may_apply() {
885 Some(EvaluatedCandidate
{
894 // If there are STILL multiple candidate, we can further
895 // reduce the list by dropping duplicates -- including
896 // resolving specializations.
897 if candidates
.len() > 1 {
899 while i
< candidates
.len() {
901 (0..candidates
.len())
903 .any(|j
| self.candidate_should_be_dropped_in_favor_of(&candidates
[i
],
906 debug
!("Dropping candidate #{}/{}: {:?}",
907 i
, candidates
.len(), candidates
[i
]);
908 candidates
.swap_remove(i
);
910 debug
!("Retaining candidate #{}/{}: {:?}",
911 i
, candidates
.len(), candidates
[i
]);
917 // If there are *STILL* multiple candidates, give up and
919 if candidates
.len() > 1 {
920 debug
!("multiple matches, ambig");
924 // If there are *NO* candidates, then there are no impls --
925 // that we know of, anyway. Note that in the case where there
926 // are unbound type variables within the obligation, it might
927 // be the case that you could still satisfy the obligation
928 // from another crate by instantiating the type variables with
929 // a type from another crate that does have an impl. This case
930 // is checked for in `evaluate_stack` (and hence users
931 // who might care about this case, like coherence, should use
933 if candidates
.is_empty() {
934 return Err(Unimplemented
);
937 // Just one candidate left.
938 self.filter_negative_impls(candidates
.pop().unwrap().candidate
)
941 fn is_knowable
<'o
>(&mut self,
942 stack
: &TraitObligationStack
<'o
, 'tcx
>)
945 debug
!("is_knowable(intercrate={})", self.intercrate
);
947 if !self.intercrate
{
951 let obligation
= &stack
.obligation
;
952 let predicate
= self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
954 // ok to skip binder because of the nature of the
955 // trait-ref-is-knowable check, which does not care about
957 let trait_ref
= &predicate
.skip_binder().trait_ref
;
959 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
962 /// Returns true if the global caches can be used.
963 /// Do note that if the type itself is not in the
964 /// global tcx, the local caches will be used.
965 fn can_use_global_caches(&self) -> bool
{
966 // If there are any where-clauses in scope, then we always use
967 // a cache local to this particular scope. Otherwise, we
968 // switch to a global cache. We used to try and draw
969 // finer-grained distinctions, but that led to a serious of
970 // annoying and weird bugs like #22019 and #18290. This simple
971 // rule seems to be pretty clearly safe and also still retains
972 // a very high hit rate (~95% when compiling rustc).
973 if !self.param_env().caller_bounds
.is_empty() {
977 // Avoid using the master cache during coherence and just rely
978 // on the local cache. This effectively disables caching
979 // during coherence. It is really just a simplification to
980 // avoid us having to fear that coherence results "pollute"
981 // the master cache. Since coherence executes pretty quickly,
982 // it's not worth going to more trouble to increase the
983 // hit-rate I don't think.
988 // Otherwise, we can use the global cache.
992 fn check_candidate_cache(&mut self,
993 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>)
994 -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>
996 let trait_ref
= &cache_fresh_trait_pred
.0.trait_ref
;
997 if self.can_use_global_caches() {
998 let cache
= self.tcx().selection_cache
.hashmap
.borrow();
999 if let Some(cached
) = cache
.get(&trait_ref
) {
1000 return Some(cached
.clone());
1003 self.infcx
.selection_cache
.hashmap
.borrow().get(trait_ref
).cloned()
1006 fn insert_candidate_cache(&mut self,
1007 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1008 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1010 let trait_ref
= cache_fresh_trait_pred
.0.trait_ref
;
1011 if self.can_use_global_caches() {
1012 let mut cache
= self.tcx().selection_cache
.hashmap
.borrow_mut();
1013 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
1014 if let Some(candidate
) = self.tcx().lift_to_global(&candidate
) {
1015 cache
.insert(trait_ref
, candidate
);
1021 self.infcx
.selection_cache
.hashmap
.borrow_mut().insert(trait_ref
, candidate
);
1024 fn should_update_candidate_cache(&mut self,
1025 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>,
1026 candidate
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1029 // In general, it's a good idea to cache results, even
1030 // ambiguous ones, to save us some trouble later. But we have
1031 // to be careful not to cache results that could be
1032 // invalidated later by advances in inference. Normally, this
1033 // is not an issue, because any inference variables whose
1034 // types are not yet bound are "freshened" in the cache key,
1035 // which means that if we later get the same request once that
1036 // type variable IS bound, we'll have a different cache key.
1037 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1038 // not yet known, we may cache the result as `None`. But if
1039 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1040 // have `Vec<Bar> : Foo` as the cache key.
1042 // HOWEVER, it CAN happen that we get an ambiguity result in
1043 // one particular case around closures where the cache key
1044 // would not change. That is when the precise types of the
1045 // upvars that a closure references have not yet been figured
1046 // out (i.e., because it is not yet known if they are captured
1047 // by ref, and if by ref, what kind of ref). In these cases,
1048 // when matching a builtin bound, we will yield back an
1049 // ambiguous result. But the *cache key* is just the closure type,
1050 // it doesn't capture the state of the upvar computation.
1052 // To avoid this trap, just don't cache ambiguous results if
1053 // the self-type contains no inference byproducts (that really
1054 // shouldn't happen in other circumstances anyway, given
1058 Ok(Some(_
)) | Err(_
) => true,
1059 Ok(None
) => cache_fresh_trait_pred
.has_infer_types()
1063 fn assemble_candidates
<'o
>(&mut self,
1064 stack
: &TraitObligationStack
<'o
, 'tcx
>)
1065 -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>>
1067 let TraitObligationStack { obligation, .. }
= *stack
;
1068 let ref obligation
= Obligation
{
1069 cause
: obligation
.cause
.clone(),
1070 recursion_depth
: obligation
.recursion_depth
,
1071 predicate
: self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
)
1074 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
1075 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1077 // This is somewhat problematic, as the current scheme can't really
1078 // handle it turning to be a projection. This does end up as truly
1079 // ambiguous in most cases anyway.
1081 // Until this is fixed, take the fast path out - this also improves
1082 // performance by preventing assemble_candidates_from_impls from
1083 // matching every impl for this trait.
1084 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
1087 let mut candidates
= SelectionCandidateSet
{
1092 // Other bounds. Consider both in-scope bounds from fn decl
1093 // and applicable impls. There is a certain set of precedence rules here.
1095 let def_id
= obligation
.predicate
.def_id();
1096 if self.tcx().lang_items
.copy_trait() == Some(def_id
) {
1097 debug
!("obligation self ty is {:?}",
1098 obligation
.predicate
.0.self_ty());
1100 // User-defined copy impls are permitted, but only for
1101 // structs and enums.
1102 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1104 // For other types, we'll use the builtin rules.
1105 let copy_conditions
= self.copy_conditions(obligation
);
1106 self.assemble_builtin_bound_candidates(copy_conditions
, &mut candidates
)?
;
1107 } else if self.tcx().lang_items
.sized_trait() == Some(def_id
) {
1108 // Sized is never implementable by end-users, it is
1109 // always automatically computed.
1110 let sized_conditions
= self.sized_conditions(obligation
);
1111 self.assemble_builtin_bound_candidates(sized_conditions
,
1113 } else if self.tcx().lang_items
.unsize_trait() == Some(def_id
) {
1114 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
1116 self.assemble_closure_candidates(obligation
, &mut candidates
)?
;
1117 self.assemble_fn_pointer_candidates(obligation
, &mut candidates
)?
;
1118 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1119 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
1122 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
1123 self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
)?
;
1124 // Default implementations have lower priority, so we only
1125 // consider triggering a default if there is no other impl that can apply.
1126 if candidates
.vec
.is_empty() {
1127 self.assemble_candidates_from_default_impls(obligation
, &mut candidates
)?
;
1129 debug
!("candidate list size: {}", candidates
.vec
.len());
1133 fn assemble_candidates_from_projected_tys(&mut self,
1134 obligation
: &TraitObligation
<'tcx
>,
1135 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1137 debug
!("assemble_candidates_for_projected_tys({:?})", obligation
);
1139 // FIXME(#20297) -- just examining the self-type is very simplistic
1141 // before we go into the whole skolemization thing, just
1142 // quickly check if the self-type is a projection at all.
1143 match obligation
.predicate
.0.trait_ref
.self_ty().sty
{
1144 ty
::TyProjection(_
) | ty
::TyAnon(..) => {}
1145 ty
::TyInfer(ty
::TyVar(_
)) => {
1146 span_bug
!(obligation
.cause
.span
,
1147 "Self=_ should have been handled by assemble_candidates");
1152 let result
= self.probe(|this
, snapshot
| {
1153 this
.match_projection_obligation_against_definition_bounds(obligation
,
1158 candidates
.vec
.push(ProjectionCandidate
);
1162 fn match_projection_obligation_against_definition_bounds(
1164 obligation
: &TraitObligation
<'tcx
>,
1165 snapshot
: &infer
::CombinedSnapshot
)
1168 let poly_trait_predicate
=
1169 self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
1170 let (skol_trait_predicate
, skol_map
) =
1171 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate
, snapshot
);
1172 debug
!("match_projection_obligation_against_definition_bounds: \
1173 skol_trait_predicate={:?} skol_map={:?}",
1174 skol_trait_predicate
,
1177 let (def_id
, substs
) = match skol_trait_predicate
.trait_ref
.self_ty().sty
{
1178 ty
::TyProjection(ref data
) => (data
.trait_ref
.def_id
, data
.trait_ref
.substs
),
1179 ty
::TyAnon(def_id
, substs
) => (def_id
, substs
),
1182 obligation
.cause
.span
,
1183 "match_projection_obligation_against_definition_bounds() called \
1184 but self-ty not a projection: {:?}",
1185 skol_trait_predicate
.trait_ref
.self_ty());
1188 debug
!("match_projection_obligation_against_definition_bounds: \
1189 def_id={:?}, substs={:?}",
1192 let item_predicates
= self.tcx().item_predicates(def_id
);
1193 let bounds
= item_predicates
.instantiate(self.tcx(), substs
);
1194 debug
!("match_projection_obligation_against_definition_bounds: \
1198 let matching_bound
=
1199 util
::elaborate_predicates(self.tcx(), bounds
.predicates
)
1203 |this
, _
| this
.match_projection(obligation
,
1205 skol_trait_predicate
.trait_ref
.clone(),
1209 debug
!("match_projection_obligation_against_definition_bounds: \
1210 matching_bound={:?}",
1212 match matching_bound
{
1215 // Repeat the successful match, if any, this time outside of a probe.
1216 let result
= self.match_projection(obligation
,
1218 skol_trait_predicate
.trait_ref
.clone(),
1222 self.infcx
.pop_skolemized(skol_map
, snapshot
);
1230 fn match_projection(&mut self,
1231 obligation
: &TraitObligation
<'tcx
>,
1232 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1233 skol_trait_ref
: ty
::TraitRef
<'tcx
>,
1234 skol_map
: &infer
::SkolemizationMap
<'tcx
>,
1235 snapshot
: &infer
::CombinedSnapshot
)
1238 assert
!(!skol_trait_ref
.has_escaping_regions());
1239 let cause
= obligation
.cause
.clone();
1240 match self.infcx
.sub_poly_trait_refs(false,
1242 trait_bound
.clone(),
1243 ty
::Binder(skol_trait_ref
.clone())) {
1244 Ok(InferOk { obligations, .. }
) => {
1245 self.inferred_obligations
.extend(obligations
);
1247 Err(_
) => { return false; }
1250 self.infcx
.leak_check(false, obligation
.cause
.span
, skol_map
, snapshot
).is_ok()
1253 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1254 /// supplied to find out whether it is listed among them.
1256 /// Never affects inference environment.
1257 fn assemble_candidates_from_caller_bounds
<'o
>(&mut self,
1258 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1259 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1260 -> Result
<(),SelectionError
<'tcx
>>
1262 debug
!("assemble_candidates_from_caller_bounds({:?})",
1266 self.param_env().caller_bounds
1268 .filter_map(|o
| o
.to_opt_poly_trait_ref());
1270 let matching_bounds
=
1272 |bound
| self.evaluate_where_clause(stack
, bound
.clone()).may_apply());
1274 let param_candidates
=
1275 matching_bounds
.map(|bound
| ParamCandidate(bound
));
1277 candidates
.vec
.extend(param_candidates
);
1282 fn evaluate_where_clause
<'o
>(&mut self,
1283 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1284 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
1287 self.probe(move |this
, _
| {
1288 match this
.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1289 Ok(obligations
) => {
1290 this
.evaluate_predicates_recursively(stack
.list(), obligations
.iter())
1292 Err(()) => EvaluatedToErr
1297 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1298 /// FnMut<..>` where `X` is a closure type.
1300 /// Note: the type parameters on a closure candidate are modeled as *output* type
1301 /// parameters and hence do not affect whether this trait is a match or not. They will be
1302 /// unified during the confirmation step.
1303 fn assemble_closure_candidates(&mut self,
1304 obligation
: &TraitObligation
<'tcx
>,
1305 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1306 -> Result
<(),SelectionError
<'tcx
>>
1308 let kind
= match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
1310 None
=> { return Ok(()); }
1313 // ok to skip binder because the substs on closure types never
1314 // touch bound regions, they just capture the in-scope
1315 // type/region parameters
1316 let self_ty
= *obligation
.self_ty().skip_binder();
1317 let (closure_def_id
, substs
) = match self_ty
.sty
{
1318 ty
::TyClosure(id
, substs
) => (id
, substs
),
1319 ty
::TyInfer(ty
::TyVar(_
)) => {
1320 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
1321 candidates
.ambiguous
= true;
1324 _
=> { return Ok(()); }
1327 debug
!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1332 match self.infcx
.closure_kind(closure_def_id
) {
1333 Some(closure_kind
) => {
1334 debug
!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind
);
1335 if closure_kind
.extends(kind
) {
1336 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1340 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
1341 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1348 /// Implement one of the `Fn()` family for a fn pointer.
1349 fn assemble_fn_pointer_candidates(&mut self,
1350 obligation
: &TraitObligation
<'tcx
>,
1351 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1352 -> Result
<(),SelectionError
<'tcx
>>
1354 // We provide impl of all fn traits for fn pointers.
1355 if self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.def_id()).is_none() {
1359 // ok to skip binder because what we are inspecting doesn't involve bound regions
1360 let self_ty
= *obligation
.self_ty().skip_binder();
1362 ty
::TyInfer(ty
::TyVar(_
)) => {
1363 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
1364 candidates
.ambiguous
= true; // could wind up being a fn() type
1367 // provide an impl, but only for suitable `fn` pointers
1368 ty
::TyFnDef(.., &ty
::BareFnTy
{
1369 unsafety
: hir
::Unsafety
::Normal
,
1373 ty
::TyFnPtr(&ty
::BareFnTy
{
1374 unsafety
: hir
::Unsafety
::Normal
,
1377 }) if !sig
.variadic() => {
1378 candidates
.vec
.push(FnPointerCandidate
);
1387 /// Search for impls that might apply to `obligation`.
1388 fn assemble_candidates_from_impls(&mut self,
1389 obligation
: &TraitObligation
<'tcx
>,
1390 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1391 -> Result
<(), SelectionError
<'tcx
>>
1393 debug
!("assemble_candidates_from_impls(obligation={:?})", obligation
);
1395 let def
= self.tcx().lookup_trait_def(obligation
.predicate
.def_id());
1397 def
.for_each_relevant_impl(
1399 obligation
.predicate
.0.trait_ref
.self_ty(),
1401 self.probe(|this
, snapshot
| { /* [1] */
1402 match this
.match_impl(impl_def_id
, obligation
, snapshot
) {
1404 candidates
.vec
.push(ImplCandidate(impl_def_id
));
1406 // NB: we can safely drop the skol map
1407 // since we are in a probe [1]
1408 mem
::drop(skol_map
);
1419 fn assemble_candidates_from_default_impls(&mut self,
1420 obligation
: &TraitObligation
<'tcx
>,
1421 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1422 -> Result
<(), SelectionError
<'tcx
>>
1424 // OK to skip binder here because the tests we do below do not involve bound regions
1425 let self_ty
= *obligation
.self_ty().skip_binder();
1426 debug
!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty
);
1428 let def_id
= obligation
.predicate
.def_id();
1430 if self.tcx().trait_has_default_impl(def_id
) {
1432 ty
::TyDynamic(..) => {
1433 // For object types, we don't know what the closed
1434 // over types are. For most traits, this means we
1435 // conservatively say nothing; a candidate may be
1436 // added by `assemble_candidates_from_object_ty`.
1437 // However, for the kind of magic reflect trait,
1438 // we consider it to be implemented even for
1439 // object types, because it just lets you reflect
1440 // onto the object type, not into the object's
1442 if self.tcx().has_attr(def_id
, "rustc_reflect_like") {
1443 candidates
.vec
.push(DefaultImplObjectCandidate(def_id
));
1447 ty
::TyProjection(..) |
1449 // In these cases, we don't know what the actual
1450 // type is. Therefore, we cannot break it down
1451 // into its constituent types. So we don't
1452 // consider the `..` impl but instead just add no
1453 // candidates: this means that typeck will only
1454 // succeed if there is another reason to believe
1455 // that this obligation holds. That could be a
1456 // where-clause or, in the case of an object type,
1457 // it could be that the object type lists the
1458 // trait (e.g. `Foo+Send : Send`). See
1459 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1460 // for an example of a test case that exercises
1463 ty
::TyInfer(ty
::TyVar(_
)) => {
1464 // the defaulted impl might apply, we don't know
1465 candidates
.ambiguous
= true;
1468 candidates
.vec
.push(DefaultImplCandidate(def_id
.clone()))
1476 /// Search for impls that might apply to `obligation`.
1477 fn assemble_candidates_from_object_ty(&mut self,
1478 obligation
: &TraitObligation
<'tcx
>,
1479 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1481 debug
!("assemble_candidates_from_object_ty(self_ty={:?})",
1482 obligation
.self_ty().skip_binder());
1484 // Object-safety candidates are only applicable to object-safe
1485 // traits. Including this check is useful because it helps
1486 // inference in cases of traits like `BorrowFrom`, which are
1487 // not object-safe, and which rely on being able to infer the
1488 // self-type from one of the other inputs. Without this check,
1489 // these cases wind up being considered ambiguous due to a
1490 // (spurious) ambiguity introduced here.
1491 let predicate_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
1492 if !self.tcx().is_object_safe(predicate_trait_ref
.def_id()) {
1496 self.probe(|this
, _snapshot
| {
1497 // the code below doesn't care about regions, and the
1498 // self-ty here doesn't escape this probe, so just erase
1500 let self_ty
= this
.tcx().erase_late_bound_regions(&obligation
.self_ty());
1501 let poly_trait_ref
= match self_ty
.sty
{
1502 ty
::TyDynamic(ref data
, ..) => {
1503 if data
.auto_traits().any(|did
| did
== obligation
.predicate
.def_id()) {
1504 debug
!("assemble_candidates_from_object_ty: matched builtin bound, \
1505 pushing candidate");
1506 candidates
.vec
.push(BuiltinObjectCandidate
);
1510 match data
.principal() {
1511 Some(p
) => p
.with_self_ty(this
.tcx(), self_ty
),
1515 ty
::TyInfer(ty
::TyVar(_
)) => {
1516 debug
!("assemble_candidates_from_object_ty: ambiguous");
1517 candidates
.ambiguous
= true; // could wind up being an object type
1525 debug
!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1528 // Count only those upcast versions that match the trait-ref
1529 // we are looking for. Specifically, do not only check for the
1530 // correct trait, but also the correct type parameters.
1531 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1532 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1533 let upcast_trait_refs
=
1534 util
::supertraits(this
.tcx(), poly_trait_ref
)
1535 .filter(|upcast_trait_ref
| {
1536 this
.probe(|this
, _
| {
1537 let upcast_trait_ref
= upcast_trait_ref
.clone();
1538 this
.match_poly_trait_ref(obligation
, upcast_trait_ref
).is_ok()
1543 if upcast_trait_refs
> 1 {
1544 // can be upcast in many ways; need more type information
1545 candidates
.ambiguous
= true;
1546 } else if upcast_trait_refs
== 1 {
1547 candidates
.vec
.push(ObjectCandidate
);
1552 /// Search for unsizing that might apply to `obligation`.
1553 fn assemble_candidates_for_unsizing(&mut self,
1554 obligation
: &TraitObligation
<'tcx
>,
1555 candidates
: &mut SelectionCandidateSet
<'tcx
>) {
1556 // We currently never consider higher-ranked obligations e.g.
1557 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1558 // because they are a priori invalid, and we could potentially add support
1559 // for them later, it's just that there isn't really a strong need for it.
1560 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1561 // impl, and those are generally applied to concrete types.
1563 // That said, one might try to write a fn with a where clause like
1564 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1565 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1566 // Still, you'd be more likely to write that where clause as
1568 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1569 // obligation above. Should be possible to extend this in the future.
1570 let source
= match self.tcx().no_late_bound_regions(&obligation
.self_ty()) {
1573 // Don't add any candidates if there are bound regions.
1577 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
1579 debug
!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1582 let may_apply
= match (&source
.sty
, &target
.sty
) {
1583 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1584 (&ty
::TyDynamic(ref data_a
, ..), &ty
::TyDynamic(ref data_b
, ..)) => {
1585 // Upcasts permit two things:
1587 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1588 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1590 // Note that neither of these changes requires any
1591 // change at runtime. Eventually this will be
1594 // We always upcast when we can because of reason
1595 // #2 (region bounds).
1596 match (data_a
.principal(), data_b
.principal()) {
1597 (Some(a
), Some(b
)) => a
.def_id() == b
.def_id() &&
1598 data_b
.auto_traits()
1599 // All of a's auto traits need to be in b's auto traits.
1600 .all(|b
| data_a
.auto_traits().any(|a
| a
== b
)),
1606 (_
, &ty
::TyDynamic(..)) => true,
1608 // Ambiguous handling is below T -> Trait, because inference
1609 // variables can still implement Unsize<Trait> and nested
1610 // obligations will have the final say (likely deferred).
1611 (&ty
::TyInfer(ty
::TyVar(_
)), _
) |
1612 (_
, &ty
::TyInfer(ty
::TyVar(_
))) => {
1613 debug
!("assemble_candidates_for_unsizing: ambiguous");
1614 candidates
.ambiguous
= true;
1619 (&ty
::TyArray(..), &ty
::TySlice(_
)) => true,
1621 // Struct<T> -> Struct<U>.
1622 (&ty
::TyAdt(def_id_a
, _
), &ty
::TyAdt(def_id_b
, _
)) if def_id_a
.is_struct() => {
1623 def_id_a
== def_id_b
1630 candidates
.vec
.push(BuiltinUnsizeCandidate
);
1634 ///////////////////////////////////////////////////////////////////////////
1637 // Winnowing is the process of attempting to resolve ambiguity by
1638 // probing further. During the winnowing process, we unify all
1639 // type variables (ignoring skolemization) and then we also
1640 // attempt to evaluate recursive bounds to see if they are
1643 /// Returns true if `candidate_i` should be dropped in favor of
1644 /// `candidate_j`. Generally speaking we will drop duplicate
1645 /// candidates and prefer where-clause candidates.
1646 /// Returns true if `victim` should be dropped in favor of
1647 /// `other`. Generally speaking we will drop duplicate
1648 /// candidates and prefer where-clause candidates.
1650 /// See the comment for "SelectionCandidate" for more details.
1651 fn candidate_should_be_dropped_in_favor_of
<'o
>(
1653 victim
: &EvaluatedCandidate
<'tcx
>,
1654 other
: &EvaluatedCandidate
<'tcx
>)
1657 if victim
.candidate
== other
.candidate
{
1661 match other
.candidate
{
1663 ParamCandidate(_
) | ProjectionCandidate
=> match victim
.candidate
{
1664 DefaultImplCandidate(..) => {
1666 "default implementations shouldn't be recorded \
1667 when there are other valid candidates");
1670 ClosureCandidate(..) |
1671 FnPointerCandidate
|
1672 BuiltinObjectCandidate
|
1673 BuiltinUnsizeCandidate
|
1674 DefaultImplObjectCandidate(..) |
1675 BuiltinCandidate { .. }
=> {
1676 // We have a where-clause so don't go around looking
1681 ProjectionCandidate
=> {
1682 // Arbitrarily give param candidates priority
1683 // over projection and object candidates.
1686 ParamCandidate(..) => false,
1688 ImplCandidate(other_def
) => {
1689 // See if we can toss out `victim` based on specialization.
1690 // This requires us to know *for sure* that the `other` impl applies
1691 // i.e. EvaluatedToOk:
1692 if other
.evaluation
== EvaluatedToOk
{
1693 if let ImplCandidate(victim_def
) = victim
.candidate
{
1694 let tcx
= self.tcx().global_tcx();
1695 return traits
::specializes(tcx
, other_def
, victim_def
);
1705 ///////////////////////////////////////////////////////////////////////////
1708 // These cover the traits that are built-in to the language
1709 // itself. This includes `Copy` and `Sized` for sure. For the
1710 // moment, it also includes `Send` / `Sync` and a few others, but
1711 // those will hopefully change to library-defined traits in the
1714 // HACK: if this returns an error, selection exits without considering
1716 fn assemble_builtin_bound_candidates
<'o
>(&mut self,
1717 conditions
: BuiltinImplConditions
<'tcx
>,
1718 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1719 -> Result
<(),SelectionError
<'tcx
>>
1722 BuiltinImplConditions
::Where(nested
) => {
1723 debug
!("builtin_bound: nested={:?}", nested
);
1724 candidates
.vec
.push(BuiltinCandidate
{
1725 has_nested
: nested
.skip_binder().len() > 0
1729 BuiltinImplConditions
::None
=> { Ok(()) }
1730 BuiltinImplConditions
::Ambiguous
=> {
1731 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1732 Ok(candidates
.ambiguous
= true)
1734 BuiltinImplConditions
::Never
=> { Err(Unimplemented) }
1738 fn sized_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1739 -> BuiltinImplConditions
<'tcx
>
1741 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1743 // NOTE: binder moved to (*)
1744 let self_ty
= self.infcx
.shallow_resolve(
1745 obligation
.predicate
.skip_binder().self_ty());
1748 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1749 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1750 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyRawPtr(..) |
1751 ty
::TyChar
| ty
::TyBox(_
) | ty
::TyRef(..) |
1752 ty
::TyArray(..) | ty
::TyClosure(..) | ty
::TyNever
|
1754 // safe for everything
1755 Where(ty
::Binder(Vec
::new()))
1758 ty
::TyStr
| ty
::TySlice(_
) | ty
::TyDynamic(..) => Never
,
1760 ty
::TyTuple(tys
) => {
1761 Where(ty
::Binder(tys
.last().into_iter().cloned().collect()))
1764 ty
::TyAdt(def
, substs
) => {
1765 let sized_crit
= def
.sized_constraint(self.tcx());
1766 // (*) binder moved here
1767 Where(ty
::Binder(match sized_crit
.sty
{
1768 ty
::TyTuple(tys
) => tys
.to_vec().subst(self.tcx(), substs
),
1769 ty
::TyBool
=> vec
![],
1770 _
=> vec
![sized_crit
.subst(self.tcx(), substs
)]
1774 ty
::TyProjection(_
) | ty
::TyParam(_
) | ty
::TyAnon(..) => None
,
1775 ty
::TyInfer(ty
::TyVar(_
)) => Ambiguous
,
1777 ty
::TyInfer(ty
::FreshTy(_
))
1778 | ty
::TyInfer(ty
::FreshIntTy(_
))
1779 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1780 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1786 fn copy_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1787 -> BuiltinImplConditions
<'tcx
>
1789 // NOTE: binder moved to (*)
1790 let self_ty
= self.infcx
.shallow_resolve(
1791 obligation
.predicate
.skip_binder().self_ty());
1793 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1796 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1797 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1798 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyChar
|
1799 ty
::TyRawPtr(..) | ty
::TyError
| ty
::TyNever
|
1800 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutImmutable }
) => {
1801 Where(ty
::Binder(Vec
::new()))
1804 ty
::TyBox(_
) | ty
::TyDynamic(..) | ty
::TyStr
| ty
::TySlice(..) |
1806 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutMutable }
) => {
1810 ty
::TyArray(element_ty
, _
) => {
1811 // (*) binder moved here
1812 Where(ty
::Binder(vec
![element_ty
]))
1815 ty
::TyTuple(tys
) => {
1816 // (*) binder moved here
1817 Where(ty
::Binder(tys
.to_vec()))
1820 ty
::TyAdt(..) | ty
::TyProjection(..) | ty
::TyParam(..) | ty
::TyAnon(..) => {
1821 // Fallback to whatever user-defined impls exist in this case.
1825 ty
::TyInfer(ty
::TyVar(_
)) => {
1826 // Unbound type variable. Might or might not have
1827 // applicable impls and so forth, depending on what
1828 // those type variables wind up being bound to.
1832 ty
::TyInfer(ty
::FreshTy(_
))
1833 | ty
::TyInfer(ty
::FreshIntTy(_
))
1834 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1835 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1841 /// For default impls, we need to break apart a type into its
1842 /// "constituent types" -- meaning, the types that it contains.
1844 /// Here are some (simple) examples:
1847 /// (i32, u32) -> [i32, u32]
1848 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1849 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1850 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1852 fn constituent_types_for_ty(&self, t
: Ty
<'tcx
>) -> Vec
<Ty
<'tcx
>> {
1862 ty
::TyInfer(ty
::IntVar(_
)) |
1863 ty
::TyInfer(ty
::FloatVar(_
)) |
1871 ty
::TyProjection(..) |
1873 ty
::TyInfer(ty
::TyVar(_
)) |
1874 ty
::TyInfer(ty
::FreshTy(_
)) |
1875 ty
::TyInfer(ty
::FreshIntTy(_
)) |
1876 ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1877 bug
!("asked to assemble constituent types of unexpected type: {:?}",
1881 ty
::TyBox(referent_ty
) => { // Box<T>
1885 ty
::TyRawPtr(ty
::TypeAndMut { ty: element_ty, ..}
) |
1886 ty
::TyRef(_
, ty
::TypeAndMut { ty: element_ty, ..}
) => {
1890 ty
::TyArray(element_ty
, _
) | ty
::TySlice(element_ty
) => {
1894 ty
::TyTuple(ref tys
) => {
1895 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1899 ty
::TyClosure(def_id
, ref substs
) => {
1900 // FIXME(#27086). We are invariant w/r/t our
1901 // func_substs, but we don't see them as
1902 // constituent types; this seems RIGHT but also like
1903 // something that a normal type couldn't simulate. Is
1904 // this just a gap with the way that PhantomData and
1905 // OIBIT interact? That is, there is no way to say
1906 // "make me invariant with respect to this TYPE, but
1907 // do not act as though I can reach it"
1908 substs
.upvar_tys(def_id
, self.tcx()).collect()
1911 // for `PhantomData<T>`, we pass `T`
1912 ty
::TyAdt(def
, substs
) if def
.is_phantom_data() => {
1913 substs
.types().collect()
1916 ty
::TyAdt(def
, substs
) => {
1918 .map(|f
| f
.ty(self.tcx(), substs
))
1924 fn collect_predicates_for_types(&mut self,
1925 cause
: ObligationCause
<'tcx
>,
1926 recursion_depth
: usize,
1927 trait_def_id
: DefId
,
1928 types
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
1929 -> Vec
<PredicateObligation
<'tcx
>>
1931 // Because the types were potentially derived from
1932 // higher-ranked obligations they may reference late-bound
1933 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1934 // yield a type like `for<'a> &'a int`. In general, we
1935 // maintain the invariant that we never manipulate bound
1936 // regions, so we have to process these bound regions somehow.
1938 // The strategy is to:
1940 // 1. Instantiate those regions to skolemized regions (e.g.,
1941 // `for<'a> &'a int` becomes `&0 int`.
1942 // 2. Produce something like `&'0 int : Copy`
1943 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1945 types
.skip_binder().into_iter().flat_map(|ty
| { // binder moved -\
1946 let ty
: ty
::Binder
<Ty
<'tcx
>> = ty
::Binder(ty
); // <----------/
1948 self.in_snapshot(|this
, snapshot
| {
1949 let (skol_ty
, skol_map
) =
1950 this
.infcx().skolemize_late_bound_regions(&ty
, snapshot
);
1951 let Normalized { value: normalized_ty, mut obligations }
=
1952 project
::normalize_with_depth(this
,
1956 let skol_obligation
=
1957 this
.tcx().predicate_for_trait_def(
1963 obligations
.push(skol_obligation
);
1964 this
.infcx().plug_leaks(skol_map
, snapshot
, obligations
)
1969 ///////////////////////////////////////////////////////////////////////////
1972 // Confirmation unifies the output type parameters of the trait
1973 // with the values found in the obligation, possibly yielding a
1974 // type error. See `README.md` for more details.
1976 fn confirm_candidate(&mut self,
1977 obligation
: &TraitObligation
<'tcx
>,
1978 candidate
: SelectionCandidate
<'tcx
>)
1979 -> Result
<Selection
<'tcx
>,SelectionError
<'tcx
>>
1981 debug
!("confirm_candidate({:?}, {:?})",
1986 BuiltinCandidate { has_nested }
=> {
1988 self.confirm_builtin_candidate(obligation
, has_nested
)))
1991 ParamCandidate(param
) => {
1992 let obligations
= self.confirm_param_candidate(obligation
, param
);
1993 Ok(VtableParam(obligations
))
1996 DefaultImplCandidate(trait_def_id
) => {
1997 let data
= self.confirm_default_impl_candidate(obligation
, trait_def_id
);
1998 Ok(VtableDefaultImpl(data
))
2001 DefaultImplObjectCandidate(trait_def_id
) => {
2002 let data
= self.confirm_default_impl_object_candidate(obligation
, trait_def_id
);
2003 Ok(VtableDefaultImpl(data
))
2006 ImplCandidate(impl_def_id
) => {
2007 Ok(VtableImpl(self.confirm_impl_candidate(obligation
, impl_def_id
)))
2010 ClosureCandidate(closure_def_id
, substs
, kind
) => {
2011 let vtable_closure
=
2012 self.confirm_closure_candidate(obligation
, closure_def_id
, substs
, kind
)?
;
2013 Ok(VtableClosure(vtable_closure
))
2016 BuiltinObjectCandidate
=> {
2017 // This indicates something like `(Trait+Send) :
2018 // Send`. In this case, we know that this holds
2019 // because that's what the object type is telling us,
2020 // and there's really no additional obligations to
2021 // prove and no types in particular to unify etc.
2022 Ok(VtableParam(Vec
::new()))
2025 ObjectCandidate
=> {
2026 let data
= self.confirm_object_candidate(obligation
);
2027 Ok(VtableObject(data
))
2030 FnPointerCandidate
=> {
2032 self.confirm_fn_pointer_candidate(obligation
)?
;
2033 Ok(VtableFnPointer(data
))
2036 ProjectionCandidate
=> {
2037 self.confirm_projection_candidate(obligation
);
2038 Ok(VtableParam(Vec
::new()))
2041 BuiltinUnsizeCandidate
=> {
2042 let data
= self.confirm_builtin_unsize_candidate(obligation
)?
;
2043 Ok(VtableBuiltin(data
))
2048 fn confirm_projection_candidate(&mut self,
2049 obligation
: &TraitObligation
<'tcx
>)
2051 self.in_snapshot(|this
, snapshot
| {
2053 this
.match_projection_obligation_against_definition_bounds(obligation
,
2059 fn confirm_param_candidate(&mut self,
2060 obligation
: &TraitObligation
<'tcx
>,
2061 param
: ty
::PolyTraitRef
<'tcx
>)
2062 -> Vec
<PredicateObligation
<'tcx
>>
2064 debug
!("confirm_param_candidate({:?},{:?})",
2068 // During evaluation, we already checked that this
2069 // where-clause trait-ref could be unified with the obligation
2070 // trait-ref. Repeat that unification now without any
2071 // transactional boundary; it should not fail.
2072 match self.match_where_clause_trait_ref(obligation
, param
.clone()) {
2073 Ok(obligations
) => obligations
,
2075 bug
!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2082 fn confirm_builtin_candidate(&mut self,
2083 obligation
: &TraitObligation
<'tcx
>,
2085 -> VtableBuiltinData
<PredicateObligation
<'tcx
>>
2087 debug
!("confirm_builtin_candidate({:?}, {:?})",
2088 obligation
, has_nested
);
2090 let obligations
= if has_nested
{
2091 let trait_def
= obligation
.predicate
.def_id();
2092 let conditions
= match trait_def
{
2093 _
if Some(trait_def
) == self.tcx().lang_items
.sized_trait() => {
2094 self.sized_conditions(obligation
)
2096 _
if Some(trait_def
) == self.tcx().lang_items
.copy_trait() => {
2097 self.copy_conditions(obligation
)
2099 _
=> bug
!("unexpected builtin trait {:?}", trait_def
)
2101 let nested
= match conditions
{
2102 BuiltinImplConditions
::Where(nested
) => nested
,
2103 _
=> bug
!("obligation {:?} had matched a builtin impl but now doesn't",
2107 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2108 self.collect_predicates_for_types(cause
,
2109 obligation
.recursion_depth
+1,
2116 debug
!("confirm_builtin_candidate: obligations={:?}",
2118 VtableBuiltinData { nested: obligations }
2121 /// This handles the case where a `impl Foo for ..` impl is being used.
2122 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2124 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2125 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2126 fn confirm_default_impl_candidate(&mut self,
2127 obligation
: &TraitObligation
<'tcx
>,
2128 trait_def_id
: DefId
)
2129 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2131 debug
!("confirm_default_impl_candidate({:?}, {:?})",
2135 // binder is moved below
2136 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2137 let types
= self.constituent_types_for_ty(self_ty
);
2138 self.vtable_default_impl(obligation
, trait_def_id
, ty
::Binder(types
))
2141 fn confirm_default_impl_object_candidate(&mut self,
2142 obligation
: &TraitObligation
<'tcx
>,
2143 trait_def_id
: DefId
)
2144 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2146 debug
!("confirm_default_impl_object_candidate({:?}, {:?})",
2150 assert
!(self.tcx().has_attr(trait_def_id
, "rustc_reflect_like"));
2152 // OK to skip binder, it is reintroduced below
2153 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2155 ty
::TyDynamic(ref data
, ..) => {
2156 // OK to skip the binder, it is reintroduced below
2157 let principal
= data
.principal().unwrap();
2158 let input_types
= principal
.input_types();
2159 let assoc_types
= data
.projection_bounds()
2160 .map(|pb
| pb
.skip_binder().ty
);
2161 let all_types
: Vec
<_
> = input_types
.chain(assoc_types
)
2164 // reintroduce the two binding levels we skipped, then flatten into one
2165 let all_types
= ty
::Binder(ty
::Binder(all_types
));
2166 let all_types
= self.tcx().flatten_late_bound_regions(&all_types
);
2168 self.vtable_default_impl(obligation
, trait_def_id
, all_types
)
2171 bug
!("asked to confirm default object implementation for non-object type: {:?}",
2177 /// See `confirm_default_impl_candidate`
2178 fn vtable_default_impl(&mut self,
2179 obligation
: &TraitObligation
<'tcx
>,
2180 trait_def_id
: DefId
,
2181 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2182 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2184 debug
!("vtable_default_impl: nested={:?}", nested
);
2186 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2187 let mut obligations
= self.collect_predicates_for_types(
2189 obligation
.recursion_depth
+1,
2193 let trait_obligations
= self.in_snapshot(|this
, snapshot
| {
2194 let poly_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
2195 let (trait_ref
, skol_map
) =
2196 this
.infcx().skolemize_late_bound_regions(&poly_trait_ref
, snapshot
);
2197 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2198 this
.impl_or_trait_obligations(cause
,
2199 obligation
.recursion_depth
+ 1,
2206 obligations
.extend(trait_obligations
);
2208 debug
!("vtable_default_impl: obligations={:?}", obligations
);
2210 VtableDefaultImplData
{
2211 trait_def_id
: trait_def_id
,
2216 fn confirm_impl_candidate(&mut self,
2217 obligation
: &TraitObligation
<'tcx
>,
2219 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2221 debug
!("confirm_impl_candidate({:?},{:?})",
2225 // First, create the substitutions by matching the impl again,
2226 // this time not in a probe.
2227 self.in_snapshot(|this
, snapshot
| {
2228 let (substs
, skol_map
) =
2229 this
.rematch_impl(impl_def_id
, obligation
,
2231 debug
!("confirm_impl_candidate substs={:?}", substs
);
2232 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2233 this
.vtable_impl(impl_def_id
, substs
, cause
,
2234 obligation
.recursion_depth
+ 1,
2239 fn vtable_impl(&mut self,
2241 mut substs
: Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2242 cause
: ObligationCause
<'tcx
>,
2243 recursion_depth
: usize,
2244 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2245 snapshot
: &infer
::CombinedSnapshot
)
2246 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2248 debug
!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2254 let mut impl_obligations
=
2255 self.impl_or_trait_obligations(cause
,
2262 debug
!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2266 // Because of RFC447, the impl-trait-ref and obligations
2267 // are sufficient to determine the impl substs, without
2268 // relying on projections in the impl-trait-ref.
2270 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2271 impl_obligations
.append(&mut substs
.obligations
);
2273 VtableImplData
{ impl_def_id
: impl_def_id
,
2274 substs
: substs
.value
,
2275 nested
: impl_obligations
}
2278 fn confirm_object_candidate(&mut self,
2279 obligation
: &TraitObligation
<'tcx
>)
2280 -> VtableObjectData
<'tcx
, PredicateObligation
<'tcx
>>
2282 debug
!("confirm_object_candidate({:?})",
2285 // FIXME skipping binder here seems wrong -- we should
2286 // probably flatten the binder from the obligation and the
2287 // binder from the object. Have to try to make a broken test
2288 // case that results. -nmatsakis
2289 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2290 let poly_trait_ref
= match self_ty
.sty
{
2291 ty
::TyDynamic(ref data
, ..) => {
2292 data
.principal().unwrap().with_self_ty(self.tcx(), self_ty
)
2295 span_bug
!(obligation
.cause
.span
,
2296 "object candidate with non-object");
2300 let mut upcast_trait_ref
= None
;
2304 let tcx
= self.tcx();
2306 // We want to find the first supertrait in the list of
2307 // supertraits that we can unify with, and do that
2308 // unification. We know that there is exactly one in the list
2309 // where we can unify because otherwise select would have
2310 // reported an ambiguity. (When we do find a match, also
2311 // record it for later.)
2313 util
::supertraits(tcx
, poly_trait_ref
)
2317 |this
, _
| this
.match_poly_trait_ref(obligation
, t
))
2319 Ok(_
) => { upcast_trait_ref = Some(t); false }
2324 // Additionally, for each of the nonmatching predicates that
2325 // we pass over, we sum up the set of number of vtable
2326 // entries, so that we can compute the offset for the selected
2329 nonmatching
.map(|t
| tcx
.count_own_vtable_entries(t
))
2335 upcast_trait_ref
: upcast_trait_ref
.unwrap(),
2336 vtable_base
: vtable_base
,
2341 fn confirm_fn_pointer_candidate(&mut self, obligation
: &TraitObligation
<'tcx
>)
2342 -> Result
<VtableFnPointerData
<'tcx
, PredicateObligation
<'tcx
>>, SelectionError
<'tcx
>>
2344 debug
!("confirm_fn_pointer_candidate({:?})",
2347 // ok to skip binder; it is reintroduced below
2348 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2349 let sig
= self_ty
.fn_sig();
2351 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2354 util
::TupleArgumentsFlag
::Yes
)
2355 .map_bound(|(trait_ref
, _
)| trait_ref
);
2357 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2358 obligation
.predicate
.to_poly_trait_ref(),
2360 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] }
)
2363 fn confirm_closure_candidate(&mut self,
2364 obligation
: &TraitObligation
<'tcx
>,
2365 closure_def_id
: DefId
,
2366 substs
: ty
::ClosureSubsts
<'tcx
>,
2367 kind
: ty
::ClosureKind
)
2368 -> Result
<VtableClosureData
<'tcx
, PredicateObligation
<'tcx
>>,
2369 SelectionError
<'tcx
>>
2371 debug
!("confirm_closure_candidate({:?},{:?},{:?})",
2379 } = self.closure_trait_ref(obligation
, closure_def_id
, substs
);
2381 debug
!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2386 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2387 obligation
.predicate
.to_poly_trait_ref(),
2390 obligations
.push(Obligation
::new(
2391 obligation
.cause
.clone(),
2392 ty
::Predicate
::ClosureKind(closure_def_id
, kind
)));
2394 Ok(VtableClosureData
{
2395 closure_def_id
: closure_def_id
,
2396 substs
: substs
.clone(),
2401 /// In the case of closure types and fn pointers,
2402 /// we currently treat the input type parameters on the trait as
2403 /// outputs. This means that when we have a match we have only
2404 /// considered the self type, so we have to go back and make sure
2405 /// to relate the argument types too. This is kind of wrong, but
2406 /// since we control the full set of impls, also not that wrong,
2407 /// and it DOES yield better error messages (since we don't report
2408 /// errors as if there is no applicable impl, but rather report
2409 /// errors are about mismatched argument types.
2411 /// Here is an example. Imagine we have a closure expression
2412 /// and we desugared it so that the type of the expression is
2413 /// `Closure`, and `Closure` expects an int as argument. Then it
2414 /// is "as if" the compiler generated this impl:
2416 /// impl Fn(int) for Closure { ... }
2418 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2419 /// we have matched the self-type `Closure`. At this point we'll
2420 /// compare the `int` to `usize` and generate an error.
2422 /// Note that this checking occurs *after* the impl has selected,
2423 /// because these output type parameters should not affect the
2424 /// selection of the impl. Therefore, if there is a mismatch, we
2425 /// report an error to the user.
2426 fn confirm_poly_trait_refs(&mut self,
2427 obligation_cause
: ObligationCause
<'tcx
>,
2428 obligation_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2429 expected_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2430 -> Result
<(), SelectionError
<'tcx
>>
2432 let obligation_trait_ref
= obligation_trait_ref
.clone();
2433 self.infcx
.sub_poly_trait_refs(false,
2434 obligation_cause
.clone(),
2435 expected_trait_ref
.clone(),
2436 obligation_trait_ref
.clone())
2437 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2438 .map_err(|e
| OutputTypeParameterMismatch(expected_trait_ref
, obligation_trait_ref
, e
))
2441 fn confirm_builtin_unsize_candidate(&mut self,
2442 obligation
: &TraitObligation
<'tcx
>,)
2443 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2444 SelectionError
<'tcx
>> {
2445 let tcx
= self.tcx();
2447 // assemble_candidates_for_unsizing should ensure there are no late bound
2448 // regions here. See the comment there for more details.
2449 let source
= self.infcx
.shallow_resolve(
2450 tcx
.no_late_bound_regions(&obligation
.self_ty()).unwrap());
2451 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
2452 let target
= self.infcx
.shallow_resolve(target
);
2454 debug
!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2457 let mut nested
= vec
![];
2458 match (&source
.sty
, &target
.sty
) {
2459 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2460 (&ty
::TyDynamic(ref data_a
, r_a
), &ty
::TyDynamic(ref data_b
, r_b
)) => {
2461 // See assemble_candidates_for_unsizing for more info.
2462 // Binders reintroduced below in call to mk_existential_predicates.
2463 let principal
= data_a
.skip_binder().principal();
2464 let iter
= principal
.into_iter().map(ty
::ExistentialPredicate
::Trait
)
2465 .chain(data_a
.skip_binder().projection_bounds()
2466 .map(|x
| ty
::ExistentialPredicate
::Projection(x
)))
2467 .chain(data_b
.auto_traits().map(ty
::ExistentialPredicate
::AutoTrait
));
2468 let new_trait
= tcx
.mk_dynamic(
2469 ty
::Binder(tcx
.mk_existential_predicates(iter
)), r_b
);
2470 let InferOk { obligations, .. }
=
2471 self.infcx
.sub_types(false, &obligation
.cause
, new_trait
, target
)
2472 .map_err(|_
| Unimplemented
)?
;
2473 self.inferred_obligations
.extend(obligations
);
2475 // Register one obligation for 'a: 'b.
2476 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2477 obligation
.cause
.body_id
,
2478 ObjectCastObligation(target
));
2479 let outlives
= ty
::OutlivesPredicate(r_a
, r_b
);
2480 nested
.push(Obligation
::with_depth(cause
,
2481 obligation
.recursion_depth
+ 1,
2482 ty
::Binder(outlives
).to_predicate()));
2486 (_
, &ty
::TyDynamic(ref data
, r
)) => {
2487 let mut object_dids
=
2488 data
.auto_traits().chain(data
.principal().map(|p
| p
.def_id()));
2489 if let Some(did
) = object_dids
.find(|did
| {
2490 !tcx
.is_object_safe(*did
)
2492 return Err(TraitNotObjectSafe(did
))
2495 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2496 obligation
.cause
.body_id
,
2497 ObjectCastObligation(target
));
2498 let mut push
= |predicate
| {
2499 nested
.push(Obligation
::with_depth(cause
.clone(),
2500 obligation
.recursion_depth
+ 1,
2504 // Create obligations:
2505 // - Casting T to Trait
2506 // - For all the various builtin bounds attached to the object cast. (In other
2507 // words, if the object type is Foo+Send, this would create an obligation for the
2509 // - Projection predicates
2510 for predicate
in data
.iter() {
2511 push(predicate
.with_self_ty(tcx
, source
));
2514 // We can only make objects from sized types.
2515 let tr
= ty
::TraitRef
{
2516 def_id
: tcx
.require_lang_item(lang_items
::SizedTraitLangItem
),
2517 substs
: tcx
.mk_substs_trait(source
, &[]),
2519 push(tr
.to_predicate());
2521 // If the type is `Foo+'a`, ensures that the type
2522 // being cast to `Foo+'a` outlives `'a`:
2523 let outlives
= ty
::OutlivesPredicate(source
, r
);
2524 push(ty
::Binder(outlives
).to_predicate());
2528 (&ty
::TyArray(a
, _
), &ty
::TySlice(b
)) => {
2529 let InferOk { obligations, .. }
=
2530 self.infcx
.sub_types(false, &obligation
.cause
, a
, b
)
2531 .map_err(|_
| Unimplemented
)?
;
2532 self.inferred_obligations
.extend(obligations
);
2535 // Struct<T> -> Struct<U>.
2536 (&ty
::TyAdt(def
, substs_a
), &ty
::TyAdt(_
, substs_b
)) => {
2539 .map(|f
| tcx
.item_type(f
.did
))
2540 .collect
::<Vec
<_
>>();
2542 // The last field of the structure has to exist and contain type parameters.
2543 let field
= if let Some(&field
) = fields
.last() {
2546 return Err(Unimplemented
);
2548 let mut ty_params
= BitVector
::new(substs_a
.types().count());
2549 let mut found
= false;
2550 for ty
in field
.walk() {
2551 if let ty
::TyParam(p
) = ty
.sty
{
2552 ty_params
.insert(p
.idx
as usize);
2557 return Err(Unimplemented
);
2560 // Replace type parameters used in unsizing with
2561 // TyError and ensure they do not affect any other fields.
2562 // This could be checked after type collection for any struct
2563 // with a potentially unsized trailing field.
2564 let params
= substs_a
.params().iter().enumerate().map(|(i
, &k
)| {
2565 if ty_params
.contains(i
) {
2566 Kind
::from(tcx
.types
.err
)
2571 let substs
= tcx
.mk_substs(params
);
2572 for &ty
in fields
.split_last().unwrap().1 {
2573 if ty
.subst(tcx
, substs
).references_error() {
2574 return Err(Unimplemented
);
2578 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2579 let inner_source
= field
.subst(tcx
, substs_a
);
2580 let inner_target
= field
.subst(tcx
, substs_b
);
2582 // Check that the source structure with the target's
2583 // type parameters is a subtype of the target.
2584 let params
= substs_a
.params().iter().enumerate().map(|(i
, &k
)| {
2585 if ty_params
.contains(i
) {
2586 Kind
::from(substs_b
.type_at(i
))
2591 let new_struct
= tcx
.mk_adt(def
, tcx
.mk_substs(params
));
2592 let InferOk { obligations, .. }
=
2593 self.infcx
.sub_types(false, &obligation
.cause
, new_struct
, target
)
2594 .map_err(|_
| Unimplemented
)?
;
2595 self.inferred_obligations
.extend(obligations
);
2597 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2598 nested
.push(tcx
.predicate_for_trait_def(
2599 obligation
.cause
.clone(),
2600 obligation
.predicate
.def_id(),
2601 obligation
.recursion_depth
+ 1,
2609 Ok(VtableBuiltinData { nested: nested }
)
2612 ///////////////////////////////////////////////////////////////////////////
2615 // Matching is a common path used for both evaluation and
2616 // confirmation. It basically unifies types that appear in impls
2617 // and traits. This does affect the surrounding environment;
2618 // therefore, when used during evaluation, match routines must be
2619 // run inside of a `probe()` so that their side-effects are
2622 fn rematch_impl(&mut self,
2624 obligation
: &TraitObligation
<'tcx
>,
2625 snapshot
: &infer
::CombinedSnapshot
)
2626 -> (Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2627 infer
::SkolemizationMap
<'tcx
>)
2629 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
2630 Ok((substs
, skol_map
)) => (substs
, skol_map
),
2632 bug
!("Impl {:?} was matchable against {:?} but now is not",
2639 fn match_impl(&mut self,
2641 obligation
: &TraitObligation
<'tcx
>,
2642 snapshot
: &infer
::CombinedSnapshot
)
2643 -> Result
<(Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2644 infer
::SkolemizationMap
<'tcx
>), ()>
2646 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2648 // Before we create the substitutions and everything, first
2649 // consider a "quick reject". This avoids creating more types
2650 // and so forth that we need to.
2651 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2655 let (skol_obligation
, skol_map
) = self.infcx().skolemize_late_bound_regions(
2656 &obligation
.predicate
,
2658 let skol_obligation_trait_ref
= skol_obligation
.trait_ref
;
2660 let impl_substs
= self.infcx
.fresh_substs_for_item(obligation
.cause
.span
,
2663 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(),
2666 let impl_trait_ref
=
2667 project
::normalize_with_depth(self,
2668 obligation
.cause
.clone(),
2669 obligation
.recursion_depth
+ 1,
2672 debug
!("match_impl(impl_def_id={:?}, obligation={:?}, \
2673 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2677 skol_obligation_trait_ref
);
2679 let InferOk { obligations, .. }
=
2680 self.infcx
.eq_trait_refs(false,
2682 impl_trait_ref
.value
.clone(),
2683 skol_obligation_trait_ref
)
2685 debug
!("match_impl: failed eq_trait_refs due to `{}`", e
);
2688 self.inferred_obligations
.extend(obligations
);
2690 if let Err(e
) = self.infcx
.leak_check(false,
2691 obligation
.cause
.span
,
2694 debug
!("match_impl: failed leak check due to `{}`", e
);
2698 debug
!("match_impl: success impl_substs={:?}", impl_substs
);
2701 obligations
: impl_trait_ref
.obligations
2705 fn fast_reject_trait_refs(&mut self,
2706 obligation
: &TraitObligation
,
2707 impl_trait_ref
: &ty
::TraitRef
)
2710 // We can avoid creating type variables and doing the full
2711 // substitution if we find that any of the input types, when
2712 // simplified, do not match.
2714 obligation
.predicate
.skip_binder().input_types()
2715 .zip(impl_trait_ref
.input_types())
2716 .any(|(obligation_ty
, impl_ty
)| {
2717 let simplified_obligation_ty
=
2718 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2719 let simplified_impl_ty
=
2720 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2722 simplified_obligation_ty
.is_some() &&
2723 simplified_impl_ty
.is_some() &&
2724 simplified_obligation_ty
!= simplified_impl_ty
2728 /// Normalize `where_clause_trait_ref` and try to match it against
2729 /// `obligation`. If successful, return any predicates that
2730 /// result from the normalization. Normalization is necessary
2731 /// because where-clauses are stored in the parameter environment
2733 fn match_where_clause_trait_ref(&mut self,
2734 obligation
: &TraitObligation
<'tcx
>,
2735 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2736 -> Result
<Vec
<PredicateObligation
<'tcx
>>,()>
2738 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)?
;
2742 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2743 /// obligation is satisfied.
2744 fn match_poly_trait_ref(&mut self,
2745 obligation
: &TraitObligation
<'tcx
>,
2746 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2749 debug
!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2753 self.infcx
.sub_poly_trait_refs(false,
2754 obligation
.cause
.clone(),
2756 obligation
.predicate
.to_poly_trait_ref())
2757 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2761 ///////////////////////////////////////////////////////////////////////////
2764 fn match_fresh_trait_refs(&self,
2765 previous
: &ty
::PolyTraitRef
<'tcx
>,
2766 current
: &ty
::PolyTraitRef
<'tcx
>)
2769 let mut matcher
= ty
::_match
::Match
::new(self.tcx());
2770 matcher
.relate(previous
, current
).is_ok()
2773 fn push_stack
<'o
,'s
:'o
>(&mut self,
2774 previous_stack
: TraitObligationStackList
<'s
, 'tcx
>,
2775 obligation
: &'o TraitObligation
<'tcx
>)
2776 -> TraitObligationStack
<'o
, 'tcx
>
2778 let fresh_trait_ref
=
2779 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2781 TraitObligationStack
{
2782 obligation
: obligation
,
2783 fresh_trait_ref
: fresh_trait_ref
,
2784 previous
: previous_stack
,
2788 fn closure_trait_ref_unnormalized(&mut self,
2789 obligation
: &TraitObligation
<'tcx
>,
2790 closure_def_id
: DefId
,
2791 substs
: ty
::ClosureSubsts
<'tcx
>)
2792 -> ty
::PolyTraitRef
<'tcx
>
2794 let closure_type
= self.infcx
.closure_type(closure_def_id
, substs
);
2795 let ty
::Binder((trait_ref
, _
)) =
2796 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2797 obligation
.predicate
.0.self_ty(), // (1)
2799 util
::TupleArgumentsFlag
::No
);
2800 // (1) Feels icky to skip the binder here, but OTOH we know
2801 // that the self-type is an unboxed closure type and hence is
2802 // in fact unparameterized (or at least does not reference any
2803 // regions bound in the obligation). Still probably some
2804 // refactoring could make this nicer.
2806 ty
::Binder(trait_ref
)
2809 fn closure_trait_ref(&mut self,
2810 obligation
: &TraitObligation
<'tcx
>,
2811 closure_def_id
: DefId
,
2812 substs
: ty
::ClosureSubsts
<'tcx
>)
2813 -> Normalized
<'tcx
, ty
::PolyTraitRef
<'tcx
>>
2815 let trait_ref
= self.closure_trait_ref_unnormalized(
2816 obligation
, closure_def_id
, substs
);
2818 // A closure signature can contain associated types which
2819 // must be normalized.
2820 normalize_with_depth(self,
2821 obligation
.cause
.clone(),
2822 obligation
.recursion_depth
+1,
2826 /// Returns the obligations that are implied by instantiating an
2827 /// impl or trait. The obligations are substituted and fully
2828 /// normalized. This is used when confirming an impl or default
2830 fn impl_or_trait_obligations(&mut self,
2831 cause
: ObligationCause
<'tcx
>,
2832 recursion_depth
: usize,
2833 def_id
: DefId
, // of impl or trait
2834 substs
: &Substs
<'tcx
>, // for impl or trait
2835 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2836 snapshot
: &infer
::CombinedSnapshot
)
2837 -> Vec
<PredicateObligation
<'tcx
>>
2839 debug
!("impl_or_trait_obligations(def_id={:?})", def_id
);
2840 let tcx
= self.tcx();
2842 // To allow for one-pass evaluation of the nested obligation,
2843 // each predicate must be preceded by the obligations required
2845 // for example, if we have:
2846 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2847 // the impl will have the following predicates:
2848 // <V as Iterator>::Item = U,
2849 // U: Iterator, U: Sized,
2850 // V: Iterator, V: Sized,
2851 // <U as Iterator>::Item: Copy
2852 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2853 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2854 // `$1: Copy`, so we must ensure the obligations are emitted in
2856 let predicates
= tcx
.item_predicates(def_id
);
2857 assert_eq
!(predicates
.parent
, None
);
2858 let predicates
= predicates
.predicates
.iter().flat_map(|predicate
| {
2859 let predicate
= normalize_with_depth(self, cause
.clone(), recursion_depth
,
2860 &predicate
.subst(tcx
, substs
));
2861 predicate
.obligations
.into_iter().chain(
2863 cause
: cause
.clone(),
2864 recursion_depth
: recursion_depth
,
2865 predicate
: predicate
.value
2868 self.infcx().plug_leaks(skol_map
, snapshot
, predicates
)
2872 impl<'tcx
> TraitObligation
<'tcx
> {
2873 #[allow(unused_comparisons)]
2874 pub fn derived_cause(&self,
2875 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>)
2876 -> ObligationCause
<'tcx
>
2879 * Creates a cause for obligations that are derived from
2880 * `obligation` by a recursive search (e.g., for a builtin
2881 * bound, or eventually a `impl Foo for ..`). If `obligation`
2882 * is itself a derived obligation, this is just a clone, but
2883 * otherwise we create a "derived obligation" cause so as to
2884 * keep track of the original root obligation for error
2888 let obligation
= self;
2890 // NOTE(flaper87): As of now, it keeps track of the whole error
2891 // chain. Ideally, we should have a way to configure this either
2892 // by using -Z verbose or just a CLI argument.
2893 if obligation
.recursion_depth
>= 0 {
2894 let derived_cause
= DerivedObligationCause
{
2895 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2896 parent_code
: Rc
::new(obligation
.cause
.code
.clone())
2898 let derived_code
= variant(derived_cause
);
2899 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2901 obligation
.cause
.clone()
2906 impl<'tcx
> SelectionCache
<'tcx
> {
2907 pub fn new() -> SelectionCache
<'tcx
> {
2909 hashmap
: RefCell
::new(FxHashMap())
2914 impl<'tcx
> EvaluationCache
<'tcx
> {
2915 pub fn new() -> EvaluationCache
<'tcx
> {
2917 hashmap
: RefCell
::new(FxHashMap())
2922 impl<'o
,'tcx
> TraitObligationStack
<'o
,'tcx
> {
2923 fn list(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2924 TraitObligationStackList
::with(self)
2927 fn iter(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2932 #[derive(Copy, Clone)]
2933 struct TraitObligationStackList
<'o
,'tcx
:'o
> {
2934 head
: Option
<&'o TraitObligationStack
<'o
,'tcx
>>
2937 impl<'o
,'tcx
> TraitObligationStackList
<'o
,'tcx
> {
2938 fn empty() -> TraitObligationStackList
<'o
,'tcx
> {
2939 TraitObligationStackList { head: None }
2942 fn with(r
: &'o TraitObligationStack
<'o
,'tcx
>) -> TraitObligationStackList
<'o
,'tcx
> {
2943 TraitObligationStackList { head: Some(r) }
2947 impl<'o
,'tcx
> Iterator
for TraitObligationStackList
<'o
,'tcx
>{
2948 type Item
= &'o TraitObligationStack
<'o
,'tcx
>;
2950 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
,'tcx
>> {
2961 impl<'o
,'tcx
> fmt
::Debug
for TraitObligationStack
<'o
,'tcx
> {
2962 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2963 write
!(f
, "TraitObligationStack({:?})", self.obligation
)
2967 impl EvaluationResult
{
2968 fn may_apply(&self) -> bool
{
2972 EvaluatedToUnknown
=> true,
2974 EvaluatedToErr
=> false
2979 impl MethodMatchResult
{
2980 pub fn may_apply(&self) -> bool
{
2982 MethodMatched(_
) => true,
2983 MethodAmbiguous(_
) => true,
2984 MethodDidNotMatch
=> false,