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 use self::SelectionCandidate
::*;
14 use self::EvaluationResult
::*;
17 use super::DerivedObligationCause
;
19 use super::project
::{normalize_with_depth, Normalized}
;
20 use super::{PredicateObligation, TraitObligation, ObligationCause}
;
21 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation}
;
22 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch}
;
23 use super::{ObjectCastObligation, Obligation}
;
24 use super::TraitNotObjectSafe
;
26 use super::SelectionResult
;
27 use super::{VtableBuiltin
, VtableImpl
, VtableParam
, VtableClosure
,
28 VtableFnPointer
, VtableObject
, VtableDefaultImpl
};
29 use super::{VtableImplData
, VtableObjectData
, VtableBuiltinData
,
30 VtableClosureData
, VtableDefaultImplData
, VtableFnPointerData
};
33 use hir
::def_id
::DefId
;
35 use infer
::{InferCtxt, InferOk, TypeFreshener}
;
36 use ty
::subst
::{Kind, Subst, Substs}
;
37 use ty
::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable}
;
40 use ty
::relate
::TypeRelation
;
41 use middle
::lang_items
;
43 use rustc_data_structures
::bitvec
::BitVector
;
44 use rustc_data_structures
::snapshot_vec
::{SnapshotVecDelegate, SnapshotVec}
;
45 use std
::cell
::RefCell
;
47 use std
::marker
::PhantomData
;
53 use util
::nodemap
::FxHashMap
;
55 struct InferredObligationsSnapshotVecDelegate
<'tcx
> {
56 phantom
: PhantomData
<&'tcx
i32>,
58 impl<'tcx
> SnapshotVecDelegate
for InferredObligationsSnapshotVecDelegate
<'tcx
> {
59 type Value
= PredicateObligation
<'tcx
>;
61 fn reverse(_
: &mut Vec
<Self::Value
>, _
: Self::Undo
) {}
64 pub struct SelectionContext
<'cx
, 'gcx
: 'cx
+'tcx
, 'tcx
: 'cx
> {
65 infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>,
67 /// Freshener used specifically for skolemizing entries on the
68 /// obligation stack. This ensures that all entries on the stack
69 /// at one time will have the same set of skolemized entries,
70 /// which is important for checking for trait bounds that
71 /// recursively require themselves.
72 freshener
: TypeFreshener
<'cx
, 'gcx
, 'tcx
>,
74 /// If true, indicates that the evaluation should be conservative
75 /// and consider the possibility of types outside this crate.
76 /// This comes up primarily when resolving ambiguity. Imagine
77 /// there is some trait reference `$0 : Bar` where `$0` is an
78 /// inference variable. If `intercrate` is true, then we can never
79 /// say for sure that this reference is not implemented, even if
80 /// there are *no impls at all for `Bar`*, because `$0` could be
81 /// bound to some type that in a downstream crate that implements
82 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
83 /// though, we set this to false, because we are only interested
84 /// in types that the user could actually have written --- in
85 /// other words, we consider `$0 : Bar` to be unimplemented if
86 /// there is no type that the user could *actually name* that
87 /// would satisfy it. This avoids crippling inference, basically.
90 inferred_obligations
: SnapshotVec
<InferredObligationsSnapshotVecDelegate
<'tcx
>>,
93 // A stack that walks back up the stack frame.
94 struct TraitObligationStack
<'prev
, 'tcx
: 'prev
> {
95 obligation
: &'prev TraitObligation
<'tcx
>,
97 /// Trait ref from `obligation` but skolemized with the
98 /// selection-context's freshener. Used to check for recursion.
99 fresh_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
101 previous
: TraitObligationStackList
<'prev
, 'tcx
>,
105 pub struct SelectionCache
<'tcx
> {
106 hashmap
: RefCell
<FxHashMap
<ty
::TraitRef
<'tcx
>,
107 SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>>,
110 /// The selection process begins by considering all impls, where
111 /// clauses, and so forth that might resolve an obligation. Sometimes
112 /// we'll be able to say definitively that (e.g.) an impl does not
113 /// apply to the obligation: perhaps it is defined for `usize` but the
114 /// obligation is for `int`. In that case, we drop the impl out of the
115 /// list. But the other cases are considered *candidates*.
117 /// For selection to succeed, there must be exactly one matching
118 /// candidate. If the obligation is fully known, this is guaranteed
119 /// by coherence. However, if the obligation contains type parameters
120 /// or variables, there may be multiple such impls.
122 /// It is not a real problem if multiple matching impls exist because
123 /// of type variables - it just means the obligation isn't sufficiently
124 /// elaborated. In that case we report an ambiguity, and the caller can
125 /// try again after more type information has been gathered or report a
126 /// "type annotations required" error.
128 /// However, with type parameters, this can be a real problem - type
129 /// parameters don't unify with regular types, but they *can* unify
130 /// with variables from blanket impls, and (unless we know its bounds
131 /// will always be satisfied) picking the blanket impl will be wrong
132 /// for at least *some* substitutions. To make this concrete, if we have
134 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
135 /// impl<T: fmt::Debug> AsDebug for T {
137 /// fn debug(self) -> fmt::Debug { self }
139 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
141 /// we can't just use the impl to resolve the <T as AsDebug> obligation
142 /// - a type from another crate (that doesn't implement fmt::Debug) could
143 /// implement AsDebug.
145 /// Because where-clauses match the type exactly, multiple clauses can
146 /// only match if there are unresolved variables, and we can mostly just
147 /// report this ambiguity in that case. This is still a problem - we can't
148 /// *do anything* with ambiguities that involve only regions. This is issue
151 /// If a single where-clause matches and there are no inference
152 /// variables left, then it definitely matches and we can just select
155 /// In fact, we even select the where-clause when the obligation contains
156 /// inference variables. The can lead to inference making "leaps of logic",
157 /// for example in this situation:
159 /// pub trait Foo<T> { fn foo(&self) -> T; }
160 /// impl<T> Foo<()> for T { fn foo(&self) { } }
161 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
163 /// pub fn foo<T>(t: T) where T: Foo<bool> {
164 /// println!("{:?}", <T as Foo<_>>::foo(&t));
166 /// fn main() { foo(false); }
168 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
169 /// impl and the where-clause. We select the where-clause and unify $0=bool,
170 /// so the program prints "false". However, if the where-clause is omitted,
171 /// the blanket impl is selected, we unify $0=(), and the program prints
174 /// Exactly the same issues apply to projection and object candidates, except
175 /// that we can have both a projection candidate and a where-clause candidate
176 /// for the same obligation. In that case either would do (except that
177 /// different "leaps of logic" would occur if inference variables are
178 /// present), and we just pick the where-clause. This is, for example,
179 /// required for associated types to work in default impls, as the bounds
180 /// are visible both as projection bounds and as where-clauses from the
181 /// parameter environment.
182 #[derive(PartialEq,Eq,Debug,Clone)]
183 enum SelectionCandidate
<'tcx
> {
184 BuiltinCandidate { has_nested: bool }
,
185 ParamCandidate(ty
::PolyTraitRef
<'tcx
>),
186 ImplCandidate(DefId
),
187 DefaultImplCandidate(DefId
),
189 /// This is a trait matching with a projected type as `Self`, and
190 /// we found an applicable bound in the trait definition.
193 /// Implementation of a `Fn`-family trait by one of the anonymous types
194 /// generated for a `||` expression. The ty::ClosureKind informs the
195 /// confirmation step what ClosureKind obligation to emit.
196 ClosureCandidate(/* closure */ DefId
, ty
::ClosureSubsts
<'tcx
>, ty
::ClosureKind
),
198 /// Implementation of a `Fn`-family trait by one of the anonymous
199 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
204 BuiltinObjectCandidate
,
206 BuiltinUnsizeCandidate
,
209 impl<'a
, 'tcx
> ty
::Lift
<'tcx
> for SelectionCandidate
<'a
> {
210 type Lifted
= SelectionCandidate
<'tcx
>;
211 fn lift_to_tcx
<'b
, 'gcx
>(&self, tcx
: TyCtxt
<'b
, 'gcx
, 'tcx
>) -> Option
<Self::Lifted
> {
213 BuiltinCandidate { has_nested }
=> {
218 ImplCandidate(def_id
) => ImplCandidate(def_id
),
219 DefaultImplCandidate(def_id
) => DefaultImplCandidate(def_id
),
220 ProjectionCandidate
=> ProjectionCandidate
,
221 FnPointerCandidate
=> FnPointerCandidate
,
222 ObjectCandidate
=> ObjectCandidate
,
223 BuiltinObjectCandidate
=> BuiltinObjectCandidate
,
224 BuiltinUnsizeCandidate
=> BuiltinUnsizeCandidate
,
226 ParamCandidate(ref trait_ref
) => {
227 return tcx
.lift(trait_ref
).map(ParamCandidate
);
229 ClosureCandidate(def_id
, ref substs
, kind
) => {
230 return tcx
.lift(substs
).map(|substs
| {
231 ClosureCandidate(def_id
, substs
, kind
)
238 struct SelectionCandidateSet
<'tcx
> {
239 // a list of candidates that definitely apply to the current
240 // obligation (meaning: types unify).
241 vec
: Vec
<SelectionCandidate
<'tcx
>>,
243 // if this is true, then there were candidates that might or might
244 // not have applied, but we couldn't tell. This occurs when some
245 // of the input types are type variables, in which case there are
246 // various "builtin" rules that might or might not trigger.
250 #[derive(PartialEq,Eq,Debug,Clone)]
251 struct EvaluatedCandidate
<'tcx
> {
252 candidate
: SelectionCandidate
<'tcx
>,
253 evaluation
: EvaluationResult
,
256 /// When does the builtin impl for `T: Trait` apply?
257 enum BuiltinImplConditions
<'tcx
> {
258 /// The impl is conditional on T1,T2,.. : Trait
259 Where(ty
::Binder
<Vec
<Ty
<'tcx
>>>),
260 /// There is no built-in impl. There may be some other
261 /// candidate (a where-clause or user-defined impl).
263 /// There is *no* impl for this, builtin or not. Ignore
264 /// all where-clauses.
266 /// It is unknown whether there is an impl.
270 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
271 /// The result of trait evaluation. The order is important
272 /// here as the evaluation of a list is the maximum of the
274 enum EvaluationResult
{
275 /// Evaluation successful
277 /// Evaluation failed because of recursion - treated as ambiguous
279 /// Evaluation is known to be ambiguous
281 /// Evaluation failed
286 pub struct EvaluationCache
<'tcx
> {
287 hashmap
: RefCell
<FxHashMap
<ty
::PolyTraitRef
<'tcx
>, EvaluationResult
>>
290 impl<'cx
, 'gcx
, 'tcx
> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
291 pub fn new(infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>) -> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
294 freshener
: infcx
.freshener(),
296 inferred_obligations
: SnapshotVec
::new(),
300 pub fn intercrate(infcx
: &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
>) -> SelectionContext
<'cx
, 'gcx
, 'tcx
> {
303 freshener
: infcx
.freshener(),
305 inferred_obligations
: SnapshotVec
::new(),
309 pub fn infcx(&self) -> &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
> {
313 pub fn tcx(&self) -> TyCtxt
<'cx
, 'gcx
, 'tcx
> {
317 pub fn closure_typer(&self) -> &'cx InferCtxt
<'cx
, 'gcx
, 'tcx
> {
321 /// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
323 fn in_snapshot
<R
, F
>(&mut self, f
: F
) -> R
324 where F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> R
326 // The irrefutable nature of the operation means we don't need to snapshot the
327 // inferred_obligations vector.
328 self.infcx
.in_snapshot(|snapshot
| f(self, snapshot
))
331 /// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
333 fn probe
<R
, F
>(&mut self, f
: F
) -> R
334 where F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> R
336 let inferred_obligations_snapshot
= self.inferred_obligations
.start_snapshot();
337 let result
= self.infcx
.probe(|snapshot
| f(self, snapshot
));
338 self.inferred_obligations
.rollback_to(inferred_obligations_snapshot
);
342 /// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
343 /// the transaction fails and s.t. old obligations are retained.
344 fn commit_if_ok
<T
, E
, F
>(&mut self, f
: F
) -> Result
<T
, E
> where
345 F
: FnOnce(&mut Self, &infer
::CombinedSnapshot
) -> Result
<T
, E
>
347 let inferred_obligations_snapshot
= self.inferred_obligations
.start_snapshot();
348 match self.infcx
.commit_if_ok(|snapshot
| f(self, snapshot
)) {
350 self.inferred_obligations
.commit(inferred_obligations_snapshot
);
354 self.inferred_obligations
.rollback_to(inferred_obligations_snapshot
);
361 ///////////////////////////////////////////////////////////////////////////
364 // The selection phase tries to identify *how* an obligation will
365 // be resolved. For example, it will identify which impl or
366 // parameter bound is to be used. The process can be inconclusive
367 // if the self type in the obligation is not fully inferred. Selection
368 // can result in an error in one of two ways:
370 // 1. If no applicable impl or parameter bound can be found.
371 // 2. If the output type parameters in the obligation do not match
372 // those specified by the impl/bound. For example, if the obligation
373 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
374 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
376 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
377 /// type environment by performing unification.
378 pub fn select(&mut self, obligation
: &TraitObligation
<'tcx
>)
379 -> SelectionResult
<'tcx
, Selection
<'tcx
>> {
380 debug
!("select({:?})", obligation
);
381 assert
!(!obligation
.predicate
.has_escaping_regions());
383 let tcx
= self.tcx();
384 let dep_node
= obligation
.predicate
.dep_node(tcx
);
385 let _task
= tcx
.dep_graph
.in_task(dep_node
);
387 let stack
= self.push_stack(TraitObligationStackList
::empty(), obligation
);
388 let ret
= match self.candidate_from_obligation(&stack
)?
{
391 let mut candidate
= self.confirm_candidate(obligation
, candidate
)?
;
392 let inferred_obligations
= (*self.inferred_obligations
).into_iter().cloned();
393 candidate
.nested_obligations_mut().extend(inferred_obligations
);
398 // Test whether this is a `()` which was produced by defaulting a
399 // diverging type variable with `!` disabled. If so, we may need
400 // to raise a warning.
401 if obligation
.predicate
.skip_binder().self_ty().is_defaulted_unit() {
402 let mut raise_warning
= true;
403 // Don't raise a warning if the trait is implemented for ! and only
404 // permits a trivial implementation for !. This stops us warning
405 // about (for example) `(): Clone` becoming `!: Clone` because such
406 // a switch can't cause code to stop compiling or execute
408 let mut never_obligation
= obligation
.clone();
409 let def_id
= never_obligation
.predicate
.skip_binder().trait_ref
.def_id
;
410 never_obligation
.predicate
= never_obligation
.predicate
.map_bound(|mut trait_pred
| {
411 // Swap out () with ! so we can check if the trait is impld for !
413 let mut trait_ref
= &mut trait_pred
.trait_ref
;
414 let unit_substs
= trait_ref
.substs
;
415 let mut never_substs
= Vec
::with_capacity(unit_substs
.len());
416 never_substs
.push(From
::from(tcx
.types
.never
));
417 never_substs
.extend(&unit_substs
[1..]);
418 trait_ref
.substs
= tcx
.intern_substs(&never_substs
);
422 if let Ok(Some(..)) = self.select(&never_obligation
) {
423 if !tcx
.trait_relevant_for_never(def_id
) {
424 // The trait is also implemented for ! and the resulting
425 // implementation cannot actually be invoked in any way.
426 raise_warning
= false;
431 tcx
.sess
.add_lint(lint
::builtin
::RESOLVE_TRAIT_ON_DEFAULTED_UNIT
,
432 obligation
.cause
.body_id
,
433 obligation
.cause
.span
,
434 format
!("code relies on type inference rules which are likely \
441 ///////////////////////////////////////////////////////////////////////////
444 // Tests whether an obligation can be selected or whether an impl
445 // can be applied to particular types. It skips the "confirmation"
446 // step and hence completely ignores output type parameters.
448 // The result is "true" if the obligation *may* hold and "false" if
449 // we can be sure it does not.
451 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
452 pub fn evaluate_obligation(&mut self,
453 obligation
: &PredicateObligation
<'tcx
>)
456 debug
!("evaluate_obligation({:?})",
459 self.probe(|this
, _
| {
460 this
.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
465 /// Evaluates whether the obligation `obligation` can be satisfied,
466 /// and returns `false` if not certain. However, this is not entirely
467 /// accurate if inference variables are involved.
468 pub fn evaluate_obligation_conservatively(&mut self,
469 obligation
: &PredicateObligation
<'tcx
>)
472 debug
!("evaluate_obligation_conservatively({:?})",
475 self.probe(|this
, _
| {
476 this
.evaluate_predicate_recursively(TraitObligationStackList
::empty(), obligation
)
481 /// Evaluates the predicates in `predicates` recursively. Note that
482 /// this applies projections in the predicates, and therefore
483 /// is run within an inference probe.
484 fn evaluate_predicates_recursively
<'a
,'o
,I
>(&mut self,
485 stack
: TraitObligationStackList
<'o
, 'tcx
>,
488 where I
: Iterator
<Item
=&'a PredicateObligation
<'tcx
>>, 'tcx
:'a
490 let mut result
= EvaluatedToOk
;
491 for obligation
in predicates
{
492 let eval
= self.evaluate_predicate_recursively(stack
, obligation
);
493 debug
!("evaluate_predicate_recursively({:?}) = {:?}",
496 EvaluatedToErr
=> { return EvaluatedToErr; }
497 EvaluatedToAmbig
=> { result = EvaluatedToAmbig; }
498 EvaluatedToUnknown
=> {
499 if result
< EvaluatedToUnknown
{
500 result
= EvaluatedToUnknown
;
509 fn evaluate_predicate_recursively
<'o
>(&mut self,
510 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
511 obligation
: &PredicateObligation
<'tcx
>)
514 debug
!("evaluate_predicate_recursively({:?})",
517 let tcx
= self.tcx();
519 // Check the cache from the tcx of predicates that we know
520 // have been proven elsewhere. This cache only contains
521 // predicates that are global in scope and hence unaffected by
522 // the current environment.
523 if tcx
.fulfilled_predicates
.borrow().check_duplicate(tcx
, &obligation
.predicate
) {
524 return EvaluatedToOk
;
527 match obligation
.predicate
{
528 ty
::Predicate
::Trait(ref t
) => {
529 assert
!(!t
.has_escaping_regions());
530 let obligation
= obligation
.with(t
.clone());
531 self.evaluate_obligation_recursively(previous_stack
, &obligation
)
534 ty
::Predicate
::Equate(ref p
) => {
535 // does this code ever run?
536 match self.infcx
.equality_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
537 Ok(InferOk { obligations, .. }
) => {
538 self.inferred_obligations
.extend(obligations
);
541 Err(_
) => EvaluatedToErr
545 ty
::Predicate
::Subtype(ref p
) => {
546 // does this code ever run?
547 match self.infcx
.subtype_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
548 Some(Ok(InferOk { obligations, .. }
)) => {
549 self.inferred_obligations
.extend(obligations
);
552 Some(Err(_
)) => EvaluatedToErr
,
553 None
=> EvaluatedToAmbig
,
557 ty
::Predicate
::WellFormed(ty
) => {
558 match ty
::wf
::obligations(self.infcx
,
559 obligation
.param_env
,
560 obligation
.cause
.body_id
,
561 ty
, obligation
.cause
.span
) {
563 self.evaluate_predicates_recursively(previous_stack
, obligations
.iter()),
569 ty
::Predicate
::TypeOutlives(..) | ty
::Predicate
::RegionOutlives(..) => {
570 // we do not consider region relationships when
571 // evaluating trait matches
575 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
576 if self.tcx().is_object_safe(trait_def_id
) {
583 ty
::Predicate
::Projection(ref data
) => {
584 let project_obligation
= obligation
.with(data
.clone());
585 match project
::poly_project_and_unify_type(self, &project_obligation
) {
586 Ok(Some(subobligations
)) => {
587 self.evaluate_predicates_recursively(previous_stack
,
588 subobligations
.iter())
599 ty
::Predicate
::ClosureKind(closure_def_id
, kind
) => {
600 match self.infcx
.closure_kind(closure_def_id
) {
601 Some(closure_kind
) => {
602 if closure_kind
.extends(kind
) {
616 fn evaluate_obligation_recursively
<'o
>(&mut self,
617 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
618 obligation
: &TraitObligation
<'tcx
>)
621 debug
!("evaluate_obligation_recursively({:?})",
624 let stack
= self.push_stack(previous_stack
, obligation
);
625 let fresh_trait_ref
= stack
.fresh_trait_ref
;
626 if let Some(result
) = self.check_evaluation_cache(obligation
.param_env
, fresh_trait_ref
) {
627 debug
!("CACHE HIT: EVAL({:?})={:?}",
633 let result
= self.evaluate_stack(&stack
);
635 debug
!("CACHE MISS: EVAL({:?})={:?}",
638 self.insert_evaluation_cache(obligation
.param_env
, fresh_trait_ref
, result
);
643 fn evaluate_stack
<'o
>(&mut self,
644 stack
: &TraitObligationStack
<'o
, 'tcx
>)
647 // In intercrate mode, whenever any of the types are unbound,
648 // there can always be an impl. Even if there are no impls in
649 // this crate, perhaps the type would be unified with
650 // something from another crate that does provide an impl.
652 // In intra mode, we must still be conservative. The reason is
653 // that we want to avoid cycles. Imagine an impl like:
655 // impl<T:Eq> Eq for Vec<T>
657 // and a trait reference like `$0 : Eq` where `$0` is an
658 // unbound variable. When we evaluate this trait-reference, we
659 // will unify `$0` with `Vec<$1>` (for some fresh variable
660 // `$1`), on the condition that `$1 : Eq`. We will then wind
661 // up with many candidates (since that are other `Eq` impls
662 // that apply) and try to winnow things down. This results in
663 // a recursive evaluation that `$1 : Eq` -- as you can
664 // imagine, this is just where we started. To avoid that, we
665 // check for unbound variables and return an ambiguous (hence possible)
666 // match if we've seen this trait before.
668 // This suffices to allow chains like `FnMut` implemented in
669 // terms of `Fn` etc, but we could probably make this more
671 let unbound_input_types
= stack
.fresh_trait_ref
.input_types().any(|ty
| ty
.is_fresh());
672 if unbound_input_types
&& self.intercrate
{
673 debug
!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
674 stack
.fresh_trait_ref
);
675 return EvaluatedToAmbig
;
677 if unbound_input_types
&&
678 stack
.iter().skip(1).any(
679 |prev
| self.match_fresh_trait_refs(&stack
.fresh_trait_ref
,
680 &prev
.fresh_trait_ref
))
682 debug
!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
683 stack
.fresh_trait_ref
);
684 return EvaluatedToUnknown
;
687 // If there is any previous entry on the stack that precisely
688 // matches this obligation, then we can assume that the
689 // obligation is satisfied for now (still all other conditions
690 // must be met of course). One obvious case this comes up is
691 // marker traits like `Send`. Think of a linked list:
693 // struct List<T> { data: T, next: Option<Box<List<T>>> {
695 // `Box<List<T>>` will be `Send` if `T` is `Send` and
696 // `Option<Box<List<T>>>` is `Send`, and in turn
697 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
700 // Note that we do this comparison using the `fresh_trait_ref`
701 // fields. Because these have all been skolemized using
702 // `self.freshener`, we can be sure that (a) this will not
703 // affect the inferencer state and (b) that if we see two
704 // skolemized types with the same index, they refer to the
705 // same unbound type variable.
708 .skip(1) // skip top-most frame
709 .any(|prev
| stack
.fresh_trait_ref
== prev
.fresh_trait_ref
)
711 debug
!("evaluate_stack({:?}) --> recursive",
712 stack
.fresh_trait_ref
);
713 return EvaluatedToOk
;
716 match self.candidate_from_obligation(stack
) {
717 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
718 Ok(None
) => EvaluatedToAmbig
,
719 Err(..) => EvaluatedToErr
723 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
724 /// obligations are met. Returns true if `candidate` remains viable after this further
726 fn evaluate_candidate
<'o
>(&mut self,
727 stack
: &TraitObligationStack
<'o
, 'tcx
>,
728 candidate
: &SelectionCandidate
<'tcx
>)
731 debug
!("evaluate_candidate: depth={} candidate={:?}",
732 stack
.obligation
.recursion_depth
, candidate
);
733 let result
= self.probe(|this
, _
| {
734 let candidate
= (*candidate
).clone();
735 match this
.confirm_candidate(stack
.obligation
, candidate
) {
737 this
.evaluate_predicates_recursively(
739 selection
.nested_obligations().iter())
741 Err(..) => EvaluatedToErr
744 debug
!("evaluate_candidate: depth={} result={:?}",
745 stack
.obligation
.recursion_depth
, result
);
749 fn check_evaluation_cache(&self,
750 param_env
: ty
::ParamEnv
<'tcx
>,
751 trait_ref
: ty
::PolyTraitRef
<'tcx
>)
752 -> Option
<EvaluationResult
>
754 if self.can_use_global_caches(param_env
) {
755 let cache
= self.tcx().evaluation_cache
.hashmap
.borrow();
756 if let Some(cached
) = cache
.get(&trait_ref
) {
757 return Some(cached
.clone());
760 self.infcx
.evaluation_cache
.hashmap
.borrow().get(&trait_ref
).cloned()
763 fn insert_evaluation_cache(&mut self,
764 param_env
: ty
::ParamEnv
<'tcx
>,
765 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
766 result
: EvaluationResult
)
768 // Avoid caching results that depend on more than just the trait-ref:
769 // The stack can create EvaluatedToUnknown, and closure signatures
770 // being yet uninferred can create "spurious" EvaluatedToAmbig
771 // and EvaluatedToOk.
772 if result
== EvaluatedToUnknown
||
773 ((result
== EvaluatedToAmbig
|| result
== EvaluatedToOk
)
774 && trait_ref
.has_closure_types())
779 if self.can_use_global_caches(param_env
) {
780 let mut cache
= self.tcx().evaluation_cache
.hashmap
.borrow_mut();
781 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
782 cache
.insert(trait_ref
, result
);
787 self.infcx
.evaluation_cache
.hashmap
.borrow_mut().insert(trait_ref
, result
);
790 ///////////////////////////////////////////////////////////////////////////
791 // CANDIDATE ASSEMBLY
793 // The selection process begins by examining all in-scope impls,
794 // caller obligations, and so forth and assembling a list of
795 // candidates. See `README.md` and the `Candidate` type for more
798 fn candidate_from_obligation
<'o
>(&mut self,
799 stack
: &TraitObligationStack
<'o
, 'tcx
>)
800 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
802 // Watch out for overflow. This intentionally bypasses (and does
803 // not update) the cache.
804 let recursion_limit
= self.infcx
.tcx
.sess
.recursion_limit
.get();
805 if stack
.obligation
.recursion_depth
>= recursion_limit
{
806 self.infcx().report_overflow_error(&stack
.obligation
, true);
809 // Check the cache. Note that we skolemize the trait-ref
810 // separately rather than using `stack.fresh_trait_ref` -- this
811 // is because we want the unbound variables to be replaced
812 // with fresh skolemized types starting from index 0.
813 let cache_fresh_trait_pred
=
814 self.infcx
.freshen(stack
.obligation
.predicate
.clone());
815 debug
!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
816 cache_fresh_trait_pred
,
818 assert
!(!stack
.obligation
.predicate
.has_escaping_regions());
820 if let Some(c
) = self.check_candidate_cache(stack
.obligation
.param_env
,
821 &cache_fresh_trait_pred
) {
822 debug
!("CACHE HIT: SELECT({:?})={:?}",
823 cache_fresh_trait_pred
,
828 // If no match, compute result and insert into cache.
829 let candidate
= self.candidate_from_obligation_no_cache(stack
);
831 if self.should_update_candidate_cache(&cache_fresh_trait_pred
, &candidate
) {
832 debug
!("CACHE MISS: SELECT({:?})={:?}",
833 cache_fresh_trait_pred
, candidate
);
834 self.insert_candidate_cache(stack
.obligation
.param_env
,
835 cache_fresh_trait_pred
,
842 // Treat negative impls as unimplemented
843 fn filter_negative_impls(&self, candidate
: SelectionCandidate
<'tcx
>)
844 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
845 if let ImplCandidate(def_id
) = candidate
{
846 if self.tcx().impl_polarity(def_id
) == hir
::ImplPolarity
::Negative
{
847 return Err(Unimplemented
)
853 fn candidate_from_obligation_no_cache
<'o
>(&mut self,
854 stack
: &TraitObligationStack
<'o
, 'tcx
>)
855 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
857 if stack
.obligation
.predicate
.references_error() {
858 // If we encounter a `TyError`, we generally prefer the
859 // most "optimistic" result in response -- that is, the
860 // one least likely to report downstream errors. But
861 // because this routine is shared by coherence and by
862 // trait selection, there isn't an obvious "right" choice
863 // here in that respect, so we opt to just return
864 // ambiguity and let the upstream clients sort it out.
868 if !self.is_knowable(stack
) {
869 debug
!("coherence stage: not knowable");
873 let candidate_set
= self.assemble_candidates(stack
)?
;
875 if candidate_set
.ambiguous
{
876 debug
!("candidate set contains ambig");
880 let mut candidates
= candidate_set
.vec
;
882 debug
!("assembled {} candidates for {:?}: {:?}",
887 // At this point, we know that each of the entries in the
888 // candidate set is *individually* applicable. Now we have to
889 // figure out if they contain mutual incompatibilities. This
890 // frequently arises if we have an unconstrained input type --
891 // for example, we are looking for $0:Eq where $0 is some
892 // unconstrained type variable. In that case, we'll get a
893 // candidate which assumes $0 == int, one that assumes $0 ==
894 // usize, etc. This spells an ambiguity.
896 // If there is more than one candidate, first winnow them down
897 // by considering extra conditions (nested obligations and so
898 // forth). We don't winnow if there is exactly one
899 // candidate. This is a relatively minor distinction but it
900 // can lead to better inference and error-reporting. An
901 // example would be if there was an impl:
903 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
905 // and we were to see some code `foo.push_clone()` where `boo`
906 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
907 // we were to winnow, we'd wind up with zero candidates.
908 // Instead, we select the right impl now but report `Bar does
909 // not implement Clone`.
910 if candidates
.len() == 1 {
911 return self.filter_negative_impls(candidates
.pop().unwrap());
914 // Winnow, but record the exact outcome of evaluation, which
915 // is needed for specialization.
916 let mut candidates
: Vec
<_
> = candidates
.into_iter().filter_map(|c
| {
917 let eval
= self.evaluate_candidate(stack
, &c
);
918 if eval
.may_apply() {
919 Some(EvaluatedCandidate
{
928 // If there are STILL multiple candidate, we can further
929 // reduce the list by dropping duplicates -- including
930 // resolving specializations.
931 if candidates
.len() > 1 {
933 while i
< candidates
.len() {
935 (0..candidates
.len())
937 .any(|j
| self.candidate_should_be_dropped_in_favor_of(&candidates
[i
],
940 debug
!("Dropping candidate #{}/{}: {:?}",
941 i
, candidates
.len(), candidates
[i
]);
942 candidates
.swap_remove(i
);
944 debug
!("Retaining candidate #{}/{}: {:?}",
945 i
, candidates
.len(), candidates
[i
]);
948 // If there are *STILL* multiple candidates, give up
949 // and report ambiguity.
951 debug
!("multiple matches, ambig");
958 // If there are *NO* candidates, then there are no impls --
959 // that we know of, anyway. Note that in the case where there
960 // are unbound type variables within the obligation, it might
961 // be the case that you could still satisfy the obligation
962 // from another crate by instantiating the type variables with
963 // a type from another crate that does have an impl. This case
964 // is checked for in `evaluate_stack` (and hence users
965 // who might care about this case, like coherence, should use
967 if candidates
.is_empty() {
968 return Err(Unimplemented
);
971 // Just one candidate left.
972 self.filter_negative_impls(candidates
.pop().unwrap().candidate
)
975 fn is_knowable
<'o
>(&mut self,
976 stack
: &TraitObligationStack
<'o
, 'tcx
>)
979 debug
!("is_knowable(intercrate={})", self.intercrate
);
981 if !self.intercrate
{
985 let obligation
= &stack
.obligation
;
986 let predicate
= self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
988 // ok to skip binder because of the nature of the
989 // trait-ref-is-knowable check, which does not care about
991 let trait_ref
= &predicate
.skip_binder().trait_ref
;
993 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
996 /// Returns true if the global caches can be used.
997 /// Do note that if the type itself is not in the
998 /// global tcx, the local caches will be used.
999 fn can_use_global_caches(&self, param_env
: ty
::ParamEnv
<'tcx
>) -> bool
{
1000 // If there are any where-clauses in scope, then we always use
1001 // a cache local to this particular scope. Otherwise, we
1002 // switch to a global cache. We used to try and draw
1003 // finer-grained distinctions, but that led to a serious of
1004 // annoying and weird bugs like #22019 and #18290. This simple
1005 // rule seems to be pretty clearly safe and also still retains
1006 // a very high hit rate (~95% when compiling rustc).
1007 if !param_env
.caller_bounds
.is_empty() {
1011 // Avoid using the master cache during coherence and just rely
1012 // on the local cache. This effectively disables caching
1013 // during coherence. It is really just a simplification to
1014 // avoid us having to fear that coherence results "pollute"
1015 // the master cache. Since coherence executes pretty quickly,
1016 // it's not worth going to more trouble to increase the
1017 // hit-rate I don't think.
1018 if self.intercrate
{
1022 // Otherwise, we can use the global cache.
1026 fn check_candidate_cache(&mut self,
1027 param_env
: ty
::ParamEnv
<'tcx
>,
1028 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>)
1029 -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>
1031 let trait_ref
= &cache_fresh_trait_pred
.0.trait_ref
;
1032 if self.can_use_global_caches(param_env
) {
1033 let cache
= self.tcx().selection_cache
.hashmap
.borrow();
1034 if let Some(cached
) = cache
.get(&trait_ref
) {
1035 return Some(cached
.clone());
1038 self.infcx
.selection_cache
.hashmap
.borrow().get(trait_ref
).cloned()
1041 fn insert_candidate_cache(&mut self,
1042 param_env
: ty
::ParamEnv
<'tcx
>,
1043 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1044 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1046 let trait_ref
= cache_fresh_trait_pred
.0.trait_ref
;
1047 if self.can_use_global_caches(param_env
) {
1048 let mut cache
= self.tcx().selection_cache
.hashmap
.borrow_mut();
1049 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
1050 if let Some(candidate
) = self.tcx().lift_to_global(&candidate
) {
1051 cache
.insert(trait_ref
, candidate
);
1057 self.infcx
.selection_cache
.hashmap
.borrow_mut().insert(trait_ref
, candidate
);
1060 fn should_update_candidate_cache(&mut self,
1061 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>,
1062 candidate
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1065 // In general, it's a good idea to cache results, even
1066 // ambiguous ones, to save us some trouble later. But we have
1067 // to be careful not to cache results that could be
1068 // invalidated later by advances in inference. Normally, this
1069 // is not an issue, because any inference variables whose
1070 // types are not yet bound are "freshened" in the cache key,
1071 // which means that if we later get the same request once that
1072 // type variable IS bound, we'll have a different cache key.
1073 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1074 // not yet known, we may cache the result as `None`. But if
1075 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1076 // have `Vec<Bar> : Foo` as the cache key.
1078 // HOWEVER, it CAN happen that we get an ambiguity result in
1079 // one particular case around closures where the cache key
1080 // would not change. That is when the precise types of the
1081 // upvars that a closure references have not yet been figured
1082 // out (i.e., because it is not yet known if they are captured
1083 // by ref, and if by ref, what kind of ref). In these cases,
1084 // when matching a builtin bound, we will yield back an
1085 // ambiguous result. But the *cache key* is just the closure type,
1086 // it doesn't capture the state of the upvar computation.
1088 // To avoid this trap, just don't cache ambiguous results if
1089 // the self-type contains no inference byproducts (that really
1090 // shouldn't happen in other circumstances anyway, given
1094 Ok(Some(_
)) | Err(_
) => true,
1095 Ok(None
) => cache_fresh_trait_pred
.has_infer_types()
1099 fn assemble_candidates
<'o
>(&mut self,
1100 stack
: &TraitObligationStack
<'o
, 'tcx
>)
1101 -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>>
1103 let TraitObligationStack { obligation, .. }
= *stack
;
1104 let ref obligation
= Obligation
{
1105 param_env
: obligation
.param_env
,
1106 cause
: obligation
.cause
.clone(),
1107 recursion_depth
: obligation
.recursion_depth
,
1108 predicate
: self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
)
1111 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
1112 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1114 // This is somewhat problematic, as the current scheme can't really
1115 // handle it turning to be a projection. This does end up as truly
1116 // ambiguous in most cases anyway.
1118 // Until this is fixed, take the fast path out - this also improves
1119 // performance by preventing assemble_candidates_from_impls from
1120 // matching every impl for this trait.
1121 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
1124 let mut candidates
= SelectionCandidateSet
{
1129 // Other bounds. Consider both in-scope bounds from fn decl
1130 // and applicable impls. There is a certain set of precedence rules here.
1132 let def_id
= obligation
.predicate
.def_id();
1133 if self.tcx().lang_items
.copy_trait() == Some(def_id
) {
1134 debug
!("obligation self ty is {:?}",
1135 obligation
.predicate
.0.self_ty());
1137 // User-defined copy impls are permitted, but only for
1138 // structs and enums.
1139 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1141 // For other types, we'll use the builtin rules.
1142 let copy_conditions
= self.copy_conditions(obligation
);
1143 self.assemble_builtin_bound_candidates(copy_conditions
, &mut candidates
)?
;
1144 } else if self.tcx().lang_items
.sized_trait() == Some(def_id
) {
1145 // Sized is never implementable by end-users, it is
1146 // always automatically computed.
1147 let sized_conditions
= self.sized_conditions(obligation
);
1148 self.assemble_builtin_bound_candidates(sized_conditions
,
1150 } else if self.tcx().lang_items
.unsize_trait() == Some(def_id
) {
1151 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
1153 self.assemble_closure_candidates(obligation
, &mut candidates
)?
;
1154 self.assemble_fn_pointer_candidates(obligation
, &mut candidates
)?
;
1155 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1156 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
1159 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
1160 self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
)?
;
1161 // Default implementations have lower priority, so we only
1162 // consider triggering a default if there is no other impl that can apply.
1163 if candidates
.vec
.is_empty() {
1164 self.assemble_candidates_from_default_impls(obligation
, &mut candidates
)?
;
1166 debug
!("candidate list size: {}", candidates
.vec
.len());
1170 fn assemble_candidates_from_projected_tys(&mut self,
1171 obligation
: &TraitObligation
<'tcx
>,
1172 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1174 debug
!("assemble_candidates_for_projected_tys({:?})", obligation
);
1176 // FIXME(#20297) -- just examining the self-type is very simplistic
1178 // before we go into the whole skolemization thing, just
1179 // quickly check if the self-type is a projection at all.
1180 match obligation
.predicate
.0.trait_ref
.self_ty().sty
{
1181 ty
::TyProjection(_
) | ty
::TyAnon(..) => {}
1182 ty
::TyInfer(ty
::TyVar(_
)) => {
1183 span_bug
!(obligation
.cause
.span
,
1184 "Self=_ should have been handled by assemble_candidates");
1189 let result
= self.probe(|this
, snapshot
| {
1190 this
.match_projection_obligation_against_definition_bounds(obligation
,
1195 candidates
.vec
.push(ProjectionCandidate
);
1199 fn match_projection_obligation_against_definition_bounds(
1201 obligation
: &TraitObligation
<'tcx
>,
1202 snapshot
: &infer
::CombinedSnapshot
)
1205 let poly_trait_predicate
=
1206 self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
1207 let (skol_trait_predicate
, skol_map
) =
1208 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate
, snapshot
);
1209 debug
!("match_projection_obligation_against_definition_bounds: \
1210 skol_trait_predicate={:?} skol_map={:?}",
1211 skol_trait_predicate
,
1214 let (def_id
, substs
) = match skol_trait_predicate
.trait_ref
.self_ty().sty
{
1215 ty
::TyProjection(ref data
) =>
1216 (data
.trait_ref(self.tcx()).def_id
, data
.substs
),
1217 ty
::TyAnon(def_id
, substs
) => (def_id
, substs
),
1220 obligation
.cause
.span
,
1221 "match_projection_obligation_against_definition_bounds() called \
1222 but self-ty not a projection: {:?}",
1223 skol_trait_predicate
.trait_ref
.self_ty());
1226 debug
!("match_projection_obligation_against_definition_bounds: \
1227 def_id={:?}, substs={:?}",
1230 let predicates_of
= self.tcx().predicates_of(def_id
);
1231 let bounds
= predicates_of
.instantiate(self.tcx(), substs
);
1232 debug
!("match_projection_obligation_against_definition_bounds: \
1236 let matching_bound
=
1237 util
::elaborate_predicates(self.tcx(), bounds
.predicates
)
1241 |this
, _
| this
.match_projection(obligation
,
1243 skol_trait_predicate
.trait_ref
.clone(),
1247 debug
!("match_projection_obligation_against_definition_bounds: \
1248 matching_bound={:?}",
1250 match matching_bound
{
1253 // Repeat the successful match, if any, this time outside of a probe.
1254 let result
= self.match_projection(obligation
,
1256 skol_trait_predicate
.trait_ref
.clone(),
1260 self.infcx
.pop_skolemized(skol_map
, snapshot
);
1268 fn match_projection(&mut self,
1269 obligation
: &TraitObligation
<'tcx
>,
1270 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1271 skol_trait_ref
: ty
::TraitRef
<'tcx
>,
1272 skol_map
: &infer
::SkolemizationMap
<'tcx
>,
1273 snapshot
: &infer
::CombinedSnapshot
)
1276 assert
!(!skol_trait_ref
.has_escaping_regions());
1277 match self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
1278 .sup(ty
::Binder(skol_trait_ref
), trait_bound
) {
1279 Ok(InferOk { obligations, .. }
) => {
1280 self.inferred_obligations
.extend(obligations
);
1282 Err(_
) => { return false; }
1285 self.infcx
.leak_check(false, obligation
.cause
.span
, skol_map
, snapshot
).is_ok()
1288 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1289 /// supplied to find out whether it is listed among them.
1291 /// Never affects inference environment.
1292 fn assemble_candidates_from_caller_bounds
<'o
>(&mut self,
1293 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1294 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1295 -> Result
<(),SelectionError
<'tcx
>>
1297 debug
!("assemble_candidates_from_caller_bounds({:?})",
1301 stack
.obligation
.param_env
.caller_bounds
1303 .filter_map(|o
| o
.to_opt_poly_trait_ref());
1305 // micro-optimization: filter out predicates relating to different
1307 let matching_bounds
=
1308 all_bounds
.filter(|p
| p
.def_id() == stack
.obligation
.predicate
.def_id());
1310 let matching_bounds
=
1311 matching_bounds
.filter(
1312 |bound
| self.evaluate_where_clause(stack
, bound
.clone()).may_apply());
1314 let param_candidates
=
1315 matching_bounds
.map(|bound
| ParamCandidate(bound
));
1317 candidates
.vec
.extend(param_candidates
);
1322 fn evaluate_where_clause
<'o
>(&mut self,
1323 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1324 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
1327 self.probe(move |this
, _
| {
1328 match this
.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1329 Ok(obligations
) => {
1330 this
.evaluate_predicates_recursively(stack
.list(), obligations
.iter())
1332 Err(()) => EvaluatedToErr
1337 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1338 /// FnMut<..>` where `X` is a closure type.
1340 /// Note: the type parameters on a closure candidate are modeled as *output* type
1341 /// parameters and hence do not affect whether this trait is a match or not. They will be
1342 /// unified during the confirmation step.
1343 fn assemble_closure_candidates(&mut self,
1344 obligation
: &TraitObligation
<'tcx
>,
1345 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1346 -> Result
<(),SelectionError
<'tcx
>>
1348 let kind
= match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
1350 None
=> { return Ok(()); }
1353 // ok to skip binder because the substs on closure types never
1354 // touch bound regions, they just capture the in-scope
1355 // type/region parameters
1356 let self_ty
= *obligation
.self_ty().skip_binder();
1357 let (closure_def_id
, substs
) = match self_ty
.sty
{
1358 ty
::TyClosure(id
, substs
) => (id
, substs
),
1359 ty
::TyInfer(ty
::TyVar(_
)) => {
1360 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
1361 candidates
.ambiguous
= true;
1364 _
=> { return Ok(()); }
1367 debug
!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1372 match self.infcx
.closure_kind(closure_def_id
) {
1373 Some(closure_kind
) => {
1374 debug
!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind
);
1375 if closure_kind
.extends(kind
) {
1376 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1380 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
1381 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1388 /// Implement one of the `Fn()` family for a fn pointer.
1389 fn assemble_fn_pointer_candidates(&mut self,
1390 obligation
: &TraitObligation
<'tcx
>,
1391 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1392 -> Result
<(),SelectionError
<'tcx
>>
1394 // We provide impl of all fn traits for fn pointers.
1395 if self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.def_id()).is_none() {
1399 // ok to skip binder because what we are inspecting doesn't involve bound regions
1400 let self_ty
= *obligation
.self_ty().skip_binder();
1402 ty
::TyInfer(ty
::TyVar(_
)) => {
1403 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
1404 candidates
.ambiguous
= true; // could wind up being a fn() type
1407 // provide an impl, but only for suitable `fn` pointers
1408 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) => {
1409 if let ty
::Binder(ty
::FnSig
{
1410 unsafety
: hir
::Unsafety
::Normal
,
1414 }) = self_ty
.fn_sig(self.tcx()) {
1415 candidates
.vec
.push(FnPointerCandidate
);
1425 /// Search for impls that might apply to `obligation`.
1426 fn assemble_candidates_from_impls(&mut self,
1427 obligation
: &TraitObligation
<'tcx
>,
1428 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1429 -> Result
<(), SelectionError
<'tcx
>>
1431 debug
!("assemble_candidates_from_impls(obligation={:?})", obligation
);
1433 self.tcx().for_each_relevant_impl(
1434 obligation
.predicate
.def_id(),
1435 obligation
.predicate
.0.trait_ref
.self_ty(),
1437 self.probe(|this
, snapshot
| { /* [1] */
1438 match this
.match_impl(impl_def_id
, obligation
, snapshot
) {
1440 candidates
.vec
.push(ImplCandidate(impl_def_id
));
1442 // NB: we can safely drop the skol map
1443 // since we are in a probe [1]
1444 mem
::drop(skol_map
);
1455 fn assemble_candidates_from_default_impls(&mut self,
1456 obligation
: &TraitObligation
<'tcx
>,
1457 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1458 -> Result
<(), SelectionError
<'tcx
>>
1460 // OK to skip binder here because the tests we do below do not involve bound regions
1461 let self_ty
= *obligation
.self_ty().skip_binder();
1462 debug
!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty
);
1464 let def_id
= obligation
.predicate
.def_id();
1466 if self.tcx().trait_has_default_impl(def_id
) {
1468 ty
::TyDynamic(..) => {
1469 // For object types, we don't know what the closed
1470 // over types are. This means we conservatively
1471 // say nothing; a candidate may be added by
1472 // `assemble_candidates_from_object_ty`.
1475 ty
::TyProjection(..) => {
1476 // In these cases, we don't know what the actual
1477 // type is. Therefore, we cannot break it down
1478 // into its constituent types. So we don't
1479 // consider the `..` impl but instead just add no
1480 // candidates: this means that typeck will only
1481 // succeed if there is another reason to believe
1482 // that this obligation holds. That could be a
1483 // where-clause or, in the case of an object type,
1484 // it could be that the object type lists the
1485 // trait (e.g. `Foo+Send : Send`). See
1486 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1487 // for an example of a test case that exercises
1490 ty
::TyInfer(ty
::TyVar(_
)) => {
1491 // the defaulted impl might apply, we don't know
1492 candidates
.ambiguous
= true;
1495 candidates
.vec
.push(DefaultImplCandidate(def_id
.clone()))
1503 /// Search for impls that might apply to `obligation`.
1504 fn assemble_candidates_from_object_ty(&mut self,
1505 obligation
: &TraitObligation
<'tcx
>,
1506 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1508 debug
!("assemble_candidates_from_object_ty(self_ty={:?})",
1509 obligation
.self_ty().skip_binder());
1511 // Object-safety candidates are only applicable to object-safe
1512 // traits. Including this check is useful because it helps
1513 // inference in cases of traits like `BorrowFrom`, which are
1514 // not object-safe, and which rely on being able to infer the
1515 // self-type from one of the other inputs. Without this check,
1516 // these cases wind up being considered ambiguous due to a
1517 // (spurious) ambiguity introduced here.
1518 let predicate_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
1519 if !self.tcx().is_object_safe(predicate_trait_ref
.def_id()) {
1523 self.probe(|this
, _snapshot
| {
1524 // the code below doesn't care about regions, and the
1525 // self-ty here doesn't escape this probe, so just erase
1527 let self_ty
= this
.tcx().erase_late_bound_regions(&obligation
.self_ty());
1528 let poly_trait_ref
= match self_ty
.sty
{
1529 ty
::TyDynamic(ref data
, ..) => {
1530 if data
.auto_traits().any(|did
| did
== obligation
.predicate
.def_id()) {
1531 debug
!("assemble_candidates_from_object_ty: matched builtin bound, \
1532 pushing candidate");
1533 candidates
.vec
.push(BuiltinObjectCandidate
);
1537 match data
.principal() {
1538 Some(p
) => p
.with_self_ty(this
.tcx(), self_ty
),
1542 ty
::TyInfer(ty
::TyVar(_
)) => {
1543 debug
!("assemble_candidates_from_object_ty: ambiguous");
1544 candidates
.ambiguous
= true; // could wind up being an object type
1552 debug
!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1555 // Count only those upcast versions that match the trait-ref
1556 // we are looking for. Specifically, do not only check for the
1557 // correct trait, but also the correct type parameters.
1558 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1559 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1560 let upcast_trait_refs
=
1561 util
::supertraits(this
.tcx(), poly_trait_ref
)
1562 .filter(|upcast_trait_ref
| {
1563 this
.probe(|this
, _
| {
1564 let upcast_trait_ref
= upcast_trait_ref
.clone();
1565 this
.match_poly_trait_ref(obligation
, upcast_trait_ref
).is_ok()
1570 if upcast_trait_refs
> 1 {
1571 // can be upcast in many ways; need more type information
1572 candidates
.ambiguous
= true;
1573 } else if upcast_trait_refs
== 1 {
1574 candidates
.vec
.push(ObjectCandidate
);
1579 /// Search for unsizing that might apply to `obligation`.
1580 fn assemble_candidates_for_unsizing(&mut self,
1581 obligation
: &TraitObligation
<'tcx
>,
1582 candidates
: &mut SelectionCandidateSet
<'tcx
>) {
1583 // We currently never consider higher-ranked obligations e.g.
1584 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1585 // because they are a priori invalid, and we could potentially add support
1586 // for them later, it's just that there isn't really a strong need for it.
1587 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1588 // impl, and those are generally applied to concrete types.
1590 // That said, one might try to write a fn with a where clause like
1591 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1592 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1593 // Still, you'd be more likely to write that where clause as
1595 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1596 // obligation above. Should be possible to extend this in the future.
1597 let source
= match self.tcx().no_late_bound_regions(&obligation
.self_ty()) {
1600 // Don't add any candidates if there are bound regions.
1604 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
1606 debug
!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1609 let may_apply
= match (&source
.sty
, &target
.sty
) {
1610 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1611 (&ty
::TyDynamic(ref data_a
, ..), &ty
::TyDynamic(ref data_b
, ..)) => {
1612 // Upcasts permit two things:
1614 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1615 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1617 // Note that neither of these changes requires any
1618 // change at runtime. Eventually this will be
1621 // We always upcast when we can because of reason
1622 // #2 (region bounds).
1623 match (data_a
.principal(), data_b
.principal()) {
1624 (Some(a
), Some(b
)) => a
.def_id() == b
.def_id() &&
1625 data_b
.auto_traits()
1626 // All of a's auto traits need to be in b's auto traits.
1627 .all(|b
| data_a
.auto_traits().any(|a
| a
== b
)),
1633 (_
, &ty
::TyDynamic(..)) => true,
1635 // Ambiguous handling is below T -> Trait, because inference
1636 // variables can still implement Unsize<Trait> and nested
1637 // obligations will have the final say (likely deferred).
1638 (&ty
::TyInfer(ty
::TyVar(_
)), _
) |
1639 (_
, &ty
::TyInfer(ty
::TyVar(_
))) => {
1640 debug
!("assemble_candidates_for_unsizing: ambiguous");
1641 candidates
.ambiguous
= true;
1646 (&ty
::TyArray(..), &ty
::TySlice(_
)) => true,
1648 // Struct<T> -> Struct<U>.
1649 (&ty
::TyAdt(def_id_a
, _
), &ty
::TyAdt(def_id_b
, _
)) if def_id_a
.is_struct() => {
1650 def_id_a
== def_id_b
1653 // (.., T) -> (.., U).
1654 (&ty
::TyTuple(tys_a
, _
), &ty
::TyTuple(tys_b
, _
)) => {
1655 tys_a
.len() == tys_b
.len()
1662 candidates
.vec
.push(BuiltinUnsizeCandidate
);
1666 ///////////////////////////////////////////////////////////////////////////
1669 // Winnowing is the process of attempting to resolve ambiguity by
1670 // probing further. During the winnowing process, we unify all
1671 // type variables (ignoring skolemization) and then we also
1672 // attempt to evaluate recursive bounds to see if they are
1675 /// Returns true if `candidate_i` should be dropped in favor of
1676 /// `candidate_j`. Generally speaking we will drop duplicate
1677 /// candidates and prefer where-clause candidates.
1678 /// Returns true if `victim` should be dropped in favor of
1679 /// `other`. Generally speaking we will drop duplicate
1680 /// candidates and prefer where-clause candidates.
1682 /// See the comment for "SelectionCandidate" for more details.
1683 fn candidate_should_be_dropped_in_favor_of
<'o
>(
1685 victim
: &EvaluatedCandidate
<'tcx
>,
1686 other
: &EvaluatedCandidate
<'tcx
>)
1689 if victim
.candidate
== other
.candidate
{
1693 match other
.candidate
{
1695 ParamCandidate(_
) | ProjectionCandidate
=> match victim
.candidate
{
1696 DefaultImplCandidate(..) => {
1698 "default implementations shouldn't be recorded \
1699 when there are other valid candidates");
1702 ClosureCandidate(..) |
1703 FnPointerCandidate
|
1704 BuiltinObjectCandidate
|
1705 BuiltinUnsizeCandidate
|
1706 BuiltinCandidate { .. }
=> {
1707 // We have a where-clause so don't go around looking
1712 ProjectionCandidate
=> {
1713 // Arbitrarily give param candidates priority
1714 // over projection and object candidates.
1717 ParamCandidate(..) => false,
1719 ImplCandidate(other_def
) => {
1720 // See if we can toss out `victim` based on specialization.
1721 // This requires us to know *for sure* that the `other` impl applies
1722 // i.e. EvaluatedToOk:
1723 if other
.evaluation
== EvaluatedToOk
{
1724 if let ImplCandidate(victim_def
) = victim
.candidate
{
1725 let tcx
= self.tcx().global_tcx();
1726 return traits
::specializes(tcx
, other_def
, victim_def
) ||
1727 tcx
.impls_are_allowed_to_overlap(other_def
, victim_def
);
1737 ///////////////////////////////////////////////////////////////////////////
1740 // These cover the traits that are built-in to the language
1741 // itself. This includes `Copy` and `Sized` for sure. For the
1742 // moment, it also includes `Send` / `Sync` and a few others, but
1743 // those will hopefully change to library-defined traits in the
1746 // HACK: if this returns an error, selection exits without considering
1748 fn assemble_builtin_bound_candidates
<'o
>(&mut self,
1749 conditions
: BuiltinImplConditions
<'tcx
>,
1750 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1751 -> Result
<(),SelectionError
<'tcx
>>
1754 BuiltinImplConditions
::Where(nested
) => {
1755 debug
!("builtin_bound: nested={:?}", nested
);
1756 candidates
.vec
.push(BuiltinCandidate
{
1757 has_nested
: nested
.skip_binder().len() > 0
1761 BuiltinImplConditions
::None
=> { Ok(()) }
1762 BuiltinImplConditions
::Ambiguous
=> {
1763 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1764 Ok(candidates
.ambiguous
= true)
1766 BuiltinImplConditions
::Never
=> { Err(Unimplemented) }
1770 fn sized_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1771 -> BuiltinImplConditions
<'tcx
>
1773 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1775 // NOTE: binder moved to (*)
1776 let self_ty
= self.infcx
.shallow_resolve(
1777 obligation
.predicate
.skip_binder().self_ty());
1780 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1781 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1782 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyRawPtr(..) |
1783 ty
::TyChar
| ty
::TyRef(..) |
1784 ty
::TyArray(..) | ty
::TyClosure(..) | ty
::TyNever
|
1786 // safe for everything
1787 Where(ty
::Binder(Vec
::new()))
1790 ty
::TyStr
| ty
::TySlice(_
) | ty
::TyDynamic(..) => Never
,
1792 ty
::TyTuple(tys
, _
) => {
1793 Where(ty
::Binder(tys
.last().into_iter().cloned().collect()))
1796 ty
::TyAdt(def
, substs
) => {
1797 let sized_crit
= def
.sized_constraint(self.tcx());
1798 // (*) binder moved here
1800 sized_crit
.iter().map(|ty
| ty
.subst(self.tcx(), substs
)).collect()
1804 ty
::TyProjection(_
) | ty
::TyParam(_
) | ty
::TyAnon(..) => None
,
1805 ty
::TyInfer(ty
::TyVar(_
)) => Ambiguous
,
1807 ty
::TyInfer(ty
::FreshTy(_
))
1808 | ty
::TyInfer(ty
::FreshIntTy(_
))
1809 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1810 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1816 fn copy_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1817 -> BuiltinImplConditions
<'tcx
>
1819 // NOTE: binder moved to (*)
1820 let self_ty
= self.infcx
.shallow_resolve(
1821 obligation
.predicate
.skip_binder().self_ty());
1823 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1826 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1827 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1828 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyChar
|
1829 ty
::TyRawPtr(..) | ty
::TyError
| ty
::TyNever
|
1830 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutImmutable }
) => {
1831 Where(ty
::Binder(Vec
::new()))
1834 ty
::TyDynamic(..) | ty
::TyStr
| ty
::TySlice(..) |
1836 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutMutable }
) => {
1840 ty
::TyArray(element_ty
, _
) => {
1841 // (*) binder moved here
1842 Where(ty
::Binder(vec
![element_ty
]))
1845 ty
::TyTuple(tys
, _
) => {
1846 // (*) binder moved here
1847 Where(ty
::Binder(tys
.to_vec()))
1850 ty
::TyAdt(..) | ty
::TyProjection(..) | ty
::TyParam(..) | ty
::TyAnon(..) => {
1851 // Fallback to whatever user-defined impls exist in this case.
1855 ty
::TyInfer(ty
::TyVar(_
)) => {
1856 // Unbound type variable. Might or might not have
1857 // applicable impls and so forth, depending on what
1858 // those type variables wind up being bound to.
1862 ty
::TyInfer(ty
::FreshTy(_
))
1863 | ty
::TyInfer(ty
::FreshIntTy(_
))
1864 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1865 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1871 /// For default impls, we need to break apart a type into its
1872 /// "constituent types" -- meaning, the types that it contains.
1874 /// Here are some (simple) examples:
1877 /// (i32, u32) -> [i32, u32]
1878 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1879 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1880 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1882 fn constituent_types_for_ty(&self, t
: Ty
<'tcx
>) -> Vec
<Ty
<'tcx
>> {
1892 ty
::TyInfer(ty
::IntVar(_
)) |
1893 ty
::TyInfer(ty
::FloatVar(_
)) |
1901 ty
::TyProjection(..) |
1902 ty
::TyInfer(ty
::TyVar(_
)) |
1903 ty
::TyInfer(ty
::FreshTy(_
)) |
1904 ty
::TyInfer(ty
::FreshIntTy(_
)) |
1905 ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1906 bug
!("asked to assemble constituent types of unexpected type: {:?}",
1910 ty
::TyRawPtr(ty
::TypeAndMut { ty: element_ty, ..}
) |
1911 ty
::TyRef(_
, ty
::TypeAndMut { ty: element_ty, ..}
) => {
1915 ty
::TyArray(element_ty
, _
) | ty
::TySlice(element_ty
) => {
1919 ty
::TyTuple(ref tys
, _
) => {
1920 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1924 ty
::TyClosure(def_id
, ref substs
) => {
1925 // FIXME(#27086). We are invariant w/r/t our
1926 // func_substs, but we don't see them as
1927 // constituent types; this seems RIGHT but also like
1928 // something that a normal type couldn't simulate. Is
1929 // this just a gap with the way that PhantomData and
1930 // OIBIT interact? That is, there is no way to say
1931 // "make me invariant with respect to this TYPE, but
1932 // do not act as though I can reach it"
1933 substs
.upvar_tys(def_id
, self.tcx()).collect()
1936 // for `PhantomData<T>`, we pass `T`
1937 ty
::TyAdt(def
, substs
) if def
.is_phantom_data() => {
1938 substs
.types().collect()
1941 ty
::TyAdt(def
, substs
) => {
1943 .map(|f
| f
.ty(self.tcx(), substs
))
1947 ty
::TyAnon(def_id
, substs
) => {
1948 // We can resolve the `impl Trait` to its concrete type,
1949 // which enforces a DAG between the functions requiring
1950 // the auto trait bounds in question.
1951 vec
![self.tcx().type_of(def_id
).subst(self.tcx(), substs
)]
1956 fn collect_predicates_for_types(&mut self,
1957 param_env
: ty
::ParamEnv
<'tcx
>,
1958 cause
: ObligationCause
<'tcx
>,
1959 recursion_depth
: usize,
1960 trait_def_id
: DefId
,
1961 types
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
1962 -> Vec
<PredicateObligation
<'tcx
>>
1964 // Because the types were potentially derived from
1965 // higher-ranked obligations they may reference late-bound
1966 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1967 // yield a type like `for<'a> &'a int`. In general, we
1968 // maintain the invariant that we never manipulate bound
1969 // regions, so we have to process these bound regions somehow.
1971 // The strategy is to:
1973 // 1. Instantiate those regions to skolemized regions (e.g.,
1974 // `for<'a> &'a int` becomes `&0 int`.
1975 // 2. Produce something like `&'0 int : Copy`
1976 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1978 types
.skip_binder().into_iter().flat_map(|ty
| { // binder moved -\
1979 let ty
: ty
::Binder
<Ty
<'tcx
>> = ty
::Binder(ty
); // <----------/
1981 self.in_snapshot(|this
, snapshot
| {
1982 let (skol_ty
, skol_map
) =
1983 this
.infcx().skolemize_late_bound_regions(&ty
, snapshot
);
1984 let Normalized { value: normalized_ty, mut obligations }
=
1985 project
::normalize_with_depth(this
,
1990 let skol_obligation
=
1991 this
.tcx().predicate_for_trait_def(param_env
,
1997 obligations
.push(skol_obligation
);
1998 this
.infcx().plug_leaks(skol_map
, snapshot
, obligations
)
2003 ///////////////////////////////////////////////////////////////////////////
2006 // Confirmation unifies the output type parameters of the trait
2007 // with the values found in the obligation, possibly yielding a
2008 // type error. See `README.md` for more details.
2010 fn confirm_candidate(&mut self,
2011 obligation
: &TraitObligation
<'tcx
>,
2012 candidate
: SelectionCandidate
<'tcx
>)
2013 -> Result
<Selection
<'tcx
>,SelectionError
<'tcx
>>
2015 debug
!("confirm_candidate({:?}, {:?})",
2020 BuiltinCandidate { has_nested }
=> {
2022 self.confirm_builtin_candidate(obligation
, has_nested
)))
2025 ParamCandidate(param
) => {
2026 let obligations
= self.confirm_param_candidate(obligation
, param
);
2027 Ok(VtableParam(obligations
))
2030 DefaultImplCandidate(trait_def_id
) => {
2031 let data
= self.confirm_default_impl_candidate(obligation
, trait_def_id
);
2032 Ok(VtableDefaultImpl(data
))
2035 ImplCandidate(impl_def_id
) => {
2036 Ok(VtableImpl(self.confirm_impl_candidate(obligation
, impl_def_id
)))
2039 ClosureCandidate(closure_def_id
, substs
, kind
) => {
2040 let vtable_closure
=
2041 self.confirm_closure_candidate(obligation
, closure_def_id
, substs
, kind
)?
;
2042 Ok(VtableClosure(vtable_closure
))
2045 BuiltinObjectCandidate
=> {
2046 // This indicates something like `(Trait+Send) :
2047 // Send`. In this case, we know that this holds
2048 // because that's what the object type is telling us,
2049 // and there's really no additional obligations to
2050 // prove and no types in particular to unify etc.
2051 Ok(VtableParam(Vec
::new()))
2054 ObjectCandidate
=> {
2055 let data
= self.confirm_object_candidate(obligation
);
2056 Ok(VtableObject(data
))
2059 FnPointerCandidate
=> {
2061 self.confirm_fn_pointer_candidate(obligation
)?
;
2062 Ok(VtableFnPointer(data
))
2065 ProjectionCandidate
=> {
2066 self.confirm_projection_candidate(obligation
);
2067 Ok(VtableParam(Vec
::new()))
2070 BuiltinUnsizeCandidate
=> {
2071 let data
= self.confirm_builtin_unsize_candidate(obligation
)?
;
2072 Ok(VtableBuiltin(data
))
2077 fn confirm_projection_candidate(&mut self,
2078 obligation
: &TraitObligation
<'tcx
>)
2080 self.in_snapshot(|this
, snapshot
| {
2082 this
.match_projection_obligation_against_definition_bounds(obligation
,
2088 fn confirm_param_candidate(&mut self,
2089 obligation
: &TraitObligation
<'tcx
>,
2090 param
: ty
::PolyTraitRef
<'tcx
>)
2091 -> Vec
<PredicateObligation
<'tcx
>>
2093 debug
!("confirm_param_candidate({:?},{:?})",
2097 // During evaluation, we already checked that this
2098 // where-clause trait-ref could be unified with the obligation
2099 // trait-ref. Repeat that unification now without any
2100 // transactional boundary; it should not fail.
2101 match self.match_where_clause_trait_ref(obligation
, param
.clone()) {
2102 Ok(obligations
) => obligations
,
2104 bug
!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2111 fn confirm_builtin_candidate(&mut self,
2112 obligation
: &TraitObligation
<'tcx
>,
2114 -> VtableBuiltinData
<PredicateObligation
<'tcx
>>
2116 debug
!("confirm_builtin_candidate({:?}, {:?})",
2117 obligation
, has_nested
);
2119 let obligations
= if has_nested
{
2120 let trait_def
= obligation
.predicate
.def_id();
2121 let conditions
= match trait_def
{
2122 _
if Some(trait_def
) == self.tcx().lang_items
.sized_trait() => {
2123 self.sized_conditions(obligation
)
2125 _
if Some(trait_def
) == self.tcx().lang_items
.copy_trait() => {
2126 self.copy_conditions(obligation
)
2128 _
=> bug
!("unexpected builtin trait {:?}", trait_def
)
2130 let nested
= match conditions
{
2131 BuiltinImplConditions
::Where(nested
) => nested
,
2132 _
=> bug
!("obligation {:?} had matched a builtin impl but now doesn't",
2136 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2137 self.collect_predicates_for_types(obligation
.param_env
,
2139 obligation
.recursion_depth
+1,
2146 debug
!("confirm_builtin_candidate: obligations={:?}",
2148 VtableBuiltinData { nested: obligations }
2151 /// This handles the case where a `impl Foo for ..` impl is being used.
2152 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2154 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2155 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2156 fn confirm_default_impl_candidate(&mut self,
2157 obligation
: &TraitObligation
<'tcx
>,
2158 trait_def_id
: DefId
)
2159 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2161 debug
!("confirm_default_impl_candidate({:?}, {:?})",
2165 // binder is moved below
2166 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2167 let types
= self.constituent_types_for_ty(self_ty
);
2168 self.vtable_default_impl(obligation
, trait_def_id
, ty
::Binder(types
))
2171 /// See `confirm_default_impl_candidate`
2172 fn vtable_default_impl(&mut self,
2173 obligation
: &TraitObligation
<'tcx
>,
2174 trait_def_id
: DefId
,
2175 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2176 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2178 debug
!("vtable_default_impl: nested={:?}", nested
);
2180 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2181 let mut obligations
= self.collect_predicates_for_types(
2182 obligation
.param_env
,
2184 obligation
.recursion_depth
+1,
2188 let trait_obligations
= self.in_snapshot(|this
, snapshot
| {
2189 let poly_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
2190 let (trait_ref
, skol_map
) =
2191 this
.infcx().skolemize_late_bound_regions(&poly_trait_ref
, snapshot
);
2192 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2193 this
.impl_or_trait_obligations(cause
,
2194 obligation
.recursion_depth
+ 1,
2195 obligation
.param_env
,
2202 obligations
.extend(trait_obligations
);
2204 debug
!("vtable_default_impl: obligations={:?}", obligations
);
2206 VtableDefaultImplData
{
2212 fn confirm_impl_candidate(&mut self,
2213 obligation
: &TraitObligation
<'tcx
>,
2215 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2217 debug
!("confirm_impl_candidate({:?},{:?})",
2221 // First, create the substitutions by matching the impl again,
2222 // this time not in a probe.
2223 self.in_snapshot(|this
, snapshot
| {
2224 let (substs
, skol_map
) =
2225 this
.rematch_impl(impl_def_id
, obligation
,
2227 debug
!("confirm_impl_candidate substs={:?}", substs
);
2228 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2229 this
.vtable_impl(impl_def_id
,
2232 obligation
.recursion_depth
+ 1,
2233 obligation
.param_env
,
2239 fn vtable_impl(&mut self,
2241 mut substs
: Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2242 cause
: ObligationCause
<'tcx
>,
2243 recursion_depth
: usize,
2244 param_env
: ty
::ParamEnv
<'tcx
>,
2245 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2246 snapshot
: &infer
::CombinedSnapshot
)
2247 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2249 debug
!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2255 let mut impl_obligations
=
2256 self.impl_or_trait_obligations(cause
,
2264 debug
!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2268 // Because of RFC447, the impl-trait-ref and obligations
2269 // are sufficient to determine the impl substs, without
2270 // relying on projections in the impl-trait-ref.
2272 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2273 impl_obligations
.append(&mut substs
.obligations
);
2275 VtableImplData
{ impl_def_id
,
2276 substs
: substs
.value
,
2277 nested
: impl_obligations
}
2280 fn confirm_object_candidate(&mut self,
2281 obligation
: &TraitObligation
<'tcx
>)
2282 -> VtableObjectData
<'tcx
, PredicateObligation
<'tcx
>>
2284 debug
!("confirm_object_candidate({:?})",
2287 // FIXME skipping binder here seems wrong -- we should
2288 // probably flatten the binder from the obligation and the
2289 // binder from the object. Have to try to make a broken test
2290 // case that results. -nmatsakis
2291 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2292 let poly_trait_ref
= match self_ty
.sty
{
2293 ty
::TyDynamic(ref data
, ..) => {
2294 data
.principal().unwrap().with_self_ty(self.tcx(), self_ty
)
2297 span_bug
!(obligation
.cause
.span
,
2298 "object candidate with non-object");
2302 let mut upcast_trait_ref
= None
;
2306 let tcx
= self.tcx();
2308 // We want to find the first supertrait in the list of
2309 // supertraits that we can unify with, and do that
2310 // unification. We know that there is exactly one in the list
2311 // where we can unify because otherwise select would have
2312 // reported an ambiguity. (When we do find a match, also
2313 // record it for later.)
2315 util
::supertraits(tcx
, poly_trait_ref
)
2319 |this
, _
| this
.match_poly_trait_ref(obligation
, t
))
2321 Ok(_
) => { upcast_trait_ref = Some(t); false }
2326 // Additionally, for each of the nonmatching predicates that
2327 // we pass over, we sum up the set of number of vtable
2328 // entries, so that we can compute the offset for the selected
2331 nonmatching
.map(|t
| tcx
.count_own_vtable_entries(t
))
2337 upcast_trait_ref
: upcast_trait_ref
.unwrap(),
2343 fn confirm_fn_pointer_candidate(&mut self, obligation
: &TraitObligation
<'tcx
>)
2344 -> Result
<VtableFnPointerData
<'tcx
, PredicateObligation
<'tcx
>>, SelectionError
<'tcx
>>
2346 debug
!("confirm_fn_pointer_candidate({:?})",
2349 // ok to skip binder; it is reintroduced below
2350 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2351 let sig
= self_ty
.fn_sig(self.tcx());
2353 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2356 util
::TupleArgumentsFlag
::Yes
)
2357 .map_bound(|(trait_ref
, _
)| trait_ref
);
2359 let Normalized { value: trait_ref, obligations }
=
2360 project
::normalize_with_depth(self,
2361 obligation
.param_env
,
2362 obligation
.cause
.clone(),
2363 obligation
.recursion_depth
+ 1,
2366 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2367 obligation
.param_env
,
2368 obligation
.predicate
.to_poly_trait_ref(),
2370 Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations }
)
2373 fn confirm_closure_candidate(&mut self,
2374 obligation
: &TraitObligation
<'tcx
>,
2375 closure_def_id
: DefId
,
2376 substs
: ty
::ClosureSubsts
<'tcx
>,
2377 kind
: ty
::ClosureKind
)
2378 -> Result
<VtableClosureData
<'tcx
, PredicateObligation
<'tcx
>>,
2379 SelectionError
<'tcx
>>
2381 debug
!("confirm_closure_candidate({:?},{:?},{:?})",
2389 } = self.closure_trait_ref(obligation
, closure_def_id
, substs
);
2391 debug
!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2396 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2397 obligation
.param_env
,
2398 obligation
.predicate
.to_poly_trait_ref(),
2401 obligations
.push(Obligation
::new(
2402 obligation
.cause
.clone(),
2403 obligation
.param_env
,
2404 ty
::Predicate
::ClosureKind(closure_def_id
, kind
)));
2406 Ok(VtableClosureData
{
2408 substs
: substs
.clone(),
2413 /// In the case of closure types and fn pointers,
2414 /// we currently treat the input type parameters on the trait as
2415 /// outputs. This means that when we have a match we have only
2416 /// considered the self type, so we have to go back and make sure
2417 /// to relate the argument types too. This is kind of wrong, but
2418 /// since we control the full set of impls, also not that wrong,
2419 /// and it DOES yield better error messages (since we don't report
2420 /// errors as if there is no applicable impl, but rather report
2421 /// errors are about mismatched argument types.
2423 /// Here is an example. Imagine we have a closure expression
2424 /// and we desugared it so that the type of the expression is
2425 /// `Closure`, and `Closure` expects an int as argument. Then it
2426 /// is "as if" the compiler generated this impl:
2428 /// impl Fn(int) for Closure { ... }
2430 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2431 /// we have matched the self-type `Closure`. At this point we'll
2432 /// compare the `int` to `usize` and generate an error.
2434 /// Note that this checking occurs *after* the impl has selected,
2435 /// because these output type parameters should not affect the
2436 /// selection of the impl. Therefore, if there is a mismatch, we
2437 /// report an error to the user.
2438 fn confirm_poly_trait_refs(&mut self,
2439 obligation_cause
: ObligationCause
<'tcx
>,
2440 obligation_param_env
: ty
::ParamEnv
<'tcx
>,
2441 obligation_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2442 expected_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2443 -> Result
<(), SelectionError
<'tcx
>>
2445 let obligation_trait_ref
= obligation_trait_ref
.clone();
2447 .at(&obligation_cause
, obligation_param_env
)
2448 .sup(obligation_trait_ref
, expected_trait_ref
)
2449 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2450 .map_err(|e
| OutputTypeParameterMismatch(expected_trait_ref
, obligation_trait_ref
, e
))
2453 fn confirm_builtin_unsize_candidate(&mut self,
2454 obligation
: &TraitObligation
<'tcx
>,)
2455 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2456 SelectionError
<'tcx
>> {
2457 let tcx
= self.tcx();
2459 // assemble_candidates_for_unsizing should ensure there are no late bound
2460 // regions here. See the comment there for more details.
2461 let source
= self.infcx
.shallow_resolve(
2462 tcx
.no_late_bound_regions(&obligation
.self_ty()).unwrap());
2463 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
2464 let target
= self.infcx
.shallow_resolve(target
);
2466 debug
!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2469 let mut nested
= vec
![];
2470 match (&source
.sty
, &target
.sty
) {
2471 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2472 (&ty
::TyDynamic(ref data_a
, r_a
), &ty
::TyDynamic(ref data_b
, r_b
)) => {
2473 // See assemble_candidates_for_unsizing for more info.
2474 // Binders reintroduced below in call to mk_existential_predicates.
2475 let principal
= data_a
.skip_binder().principal();
2476 let iter
= principal
.into_iter().map(ty
::ExistentialPredicate
::Trait
)
2477 .chain(data_a
.skip_binder().projection_bounds()
2478 .map(|x
| ty
::ExistentialPredicate
::Projection(x
)))
2479 .chain(data_b
.auto_traits().map(ty
::ExistentialPredicate
::AutoTrait
));
2480 let new_trait
= tcx
.mk_dynamic(
2481 ty
::Binder(tcx
.mk_existential_predicates(iter
)), r_b
);
2482 let InferOk { obligations, .. }
=
2483 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2484 .eq(target
, new_trait
)
2485 .map_err(|_
| Unimplemented
)?
;
2486 self.inferred_obligations
.extend(obligations
);
2488 // Register one obligation for 'a: 'b.
2489 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2490 obligation
.cause
.body_id
,
2491 ObjectCastObligation(target
));
2492 let outlives
= ty
::OutlivesPredicate(r_a
, r_b
);
2493 nested
.push(Obligation
::with_depth(cause
,
2494 obligation
.recursion_depth
+ 1,
2495 obligation
.param_env
,
2496 ty
::Binder(outlives
).to_predicate()));
2500 (_
, &ty
::TyDynamic(ref data
, r
)) => {
2501 let mut object_dids
=
2502 data
.auto_traits().chain(data
.principal().map(|p
| p
.def_id()));
2503 if let Some(did
) = object_dids
.find(|did
| {
2504 !tcx
.is_object_safe(*did
)
2506 return Err(TraitNotObjectSafe(did
))
2509 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2510 obligation
.cause
.body_id
,
2511 ObjectCastObligation(target
));
2512 let mut push
= |predicate
| {
2513 nested
.push(Obligation
::with_depth(cause
.clone(),
2514 obligation
.recursion_depth
+ 1,
2515 obligation
.param_env
,
2519 // Create obligations:
2520 // - Casting T to Trait
2521 // - For all the various builtin bounds attached to the object cast. (In other
2522 // words, if the object type is Foo+Send, this would create an obligation for the
2524 // - Projection predicates
2525 for predicate
in data
.iter() {
2526 push(predicate
.with_self_ty(tcx
, source
));
2529 // We can only make objects from sized types.
2530 let tr
= ty
::TraitRef
{
2531 def_id
: tcx
.require_lang_item(lang_items
::SizedTraitLangItem
),
2532 substs
: tcx
.mk_substs_trait(source
, &[]),
2534 push(tr
.to_predicate());
2536 // If the type is `Foo+'a`, ensures that the type
2537 // being cast to `Foo+'a` outlives `'a`:
2538 let outlives
= ty
::OutlivesPredicate(source
, r
);
2539 push(ty
::Binder(outlives
).to_predicate());
2543 (&ty
::TyArray(a
, _
), &ty
::TySlice(b
)) => {
2544 let InferOk { obligations, .. }
=
2545 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2547 .map_err(|_
| Unimplemented
)?
;
2548 self.inferred_obligations
.extend(obligations
);
2551 // Struct<T> -> Struct<U>.
2552 (&ty
::TyAdt(def
, substs_a
), &ty
::TyAdt(_
, substs_b
)) => {
2555 .map(|f
| tcx
.type_of(f
.did
))
2556 .collect
::<Vec
<_
>>();
2558 // The last field of the structure has to exist and contain type parameters.
2559 let field
= if let Some(&field
) = fields
.last() {
2562 return Err(Unimplemented
);
2564 let mut ty_params
= BitVector
::new(substs_a
.types().count());
2565 let mut found
= false;
2566 for ty
in field
.walk() {
2567 if let ty
::TyParam(p
) = ty
.sty
{
2568 ty_params
.insert(p
.idx
as usize);
2573 return Err(Unimplemented
);
2576 // Replace type parameters used in unsizing with
2577 // TyError and ensure they do not affect any other fields.
2578 // This could be checked after type collection for any struct
2579 // with a potentially unsized trailing field.
2580 let params
= substs_a
.iter().enumerate().map(|(i
, &k
)| {
2581 if ty_params
.contains(i
) {
2582 Kind
::from(tcx
.types
.err
)
2587 let substs
= tcx
.mk_substs(params
);
2588 for &ty
in fields
.split_last().unwrap().1 {
2589 if ty
.subst(tcx
, substs
).references_error() {
2590 return Err(Unimplemented
);
2594 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2595 let inner_source
= field
.subst(tcx
, substs_a
);
2596 let inner_target
= field
.subst(tcx
, substs_b
);
2598 // Check that the source struct with the target's
2599 // unsized parameters is equal to the target.
2600 let params
= substs_a
.iter().enumerate().map(|(i
, &k
)| {
2601 if ty_params
.contains(i
) {
2602 Kind
::from(substs_b
.type_at(i
))
2607 let new_struct
= tcx
.mk_adt(def
, tcx
.mk_substs(params
));
2608 let InferOk { obligations, .. }
=
2609 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2610 .eq(target
, new_struct
)
2611 .map_err(|_
| Unimplemented
)?
;
2612 self.inferred_obligations
.extend(obligations
);
2614 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2615 nested
.push(tcx
.predicate_for_trait_def(
2616 obligation
.param_env
,
2617 obligation
.cause
.clone(),
2618 obligation
.predicate
.def_id(),
2619 obligation
.recursion_depth
+ 1,
2624 // (.., T) -> (.., U).
2625 (&ty
::TyTuple(tys_a
, _
), &ty
::TyTuple(tys_b
, _
)) => {
2626 assert_eq
!(tys_a
.len(), tys_b
.len());
2628 // The last field of the tuple has to exist.
2629 let (a_last
, a_mid
) = if let Some(x
) = tys_a
.split_last() {
2632 return Err(Unimplemented
);
2634 let b_last
= tys_b
.last().unwrap();
2636 // Check that the source tuple with the target's
2637 // last element is equal to the target.
2638 let new_tuple
= tcx
.mk_tup(a_mid
.iter().chain(Some(b_last
)), false);
2639 let InferOk { obligations, .. }
=
2640 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2641 .eq(target
, new_tuple
)
2642 .map_err(|_
| Unimplemented
)?
;
2643 self.inferred_obligations
.extend(obligations
);
2645 // Construct the nested T: Unsize<U> predicate.
2646 nested
.push(tcx
.predicate_for_trait_def(
2647 obligation
.param_env
,
2648 obligation
.cause
.clone(),
2649 obligation
.predicate
.def_id(),
2650 obligation
.recursion_depth
+ 1,
2658 Ok(VtableBuiltinData { nested: nested }
)
2661 ///////////////////////////////////////////////////////////////////////////
2664 // Matching is a common path used for both evaluation and
2665 // confirmation. It basically unifies types that appear in impls
2666 // and traits. This does affect the surrounding environment;
2667 // therefore, when used during evaluation, match routines must be
2668 // run inside of a `probe()` so that their side-effects are
2671 fn rematch_impl(&mut self,
2673 obligation
: &TraitObligation
<'tcx
>,
2674 snapshot
: &infer
::CombinedSnapshot
)
2675 -> (Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2676 infer
::SkolemizationMap
<'tcx
>)
2678 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
2679 Ok((substs
, skol_map
)) => (substs
, skol_map
),
2681 bug
!("Impl {:?} was matchable against {:?} but now is not",
2688 fn match_impl(&mut self,
2690 obligation
: &TraitObligation
<'tcx
>,
2691 snapshot
: &infer
::CombinedSnapshot
)
2692 -> Result
<(Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2693 infer
::SkolemizationMap
<'tcx
>), ()>
2695 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2697 // Before we create the substitutions and everything, first
2698 // consider a "quick reject". This avoids creating more types
2699 // and so forth that we need to.
2700 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2704 let (skol_obligation
, skol_map
) = self.infcx().skolemize_late_bound_regions(
2705 &obligation
.predicate
,
2707 let skol_obligation_trait_ref
= skol_obligation
.trait_ref
;
2709 let impl_substs
= self.infcx
.fresh_substs_for_item(obligation
.cause
.span
,
2712 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(),
2715 let impl_trait_ref
=
2716 project
::normalize_with_depth(self,
2717 obligation
.param_env
,
2718 obligation
.cause
.clone(),
2719 obligation
.recursion_depth
+ 1,
2722 debug
!("match_impl(impl_def_id={:?}, obligation={:?}, \
2723 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2727 skol_obligation_trait_ref
);
2729 let InferOk { obligations, .. }
=
2730 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2731 .eq(skol_obligation_trait_ref
, impl_trait_ref
.value
)
2733 debug
!("match_impl: failed eq_trait_refs due to `{}`", e
);
2736 self.inferred_obligations
.extend(obligations
);
2738 if let Err(e
) = self.infcx
.leak_check(false,
2739 obligation
.cause
.span
,
2742 debug
!("match_impl: failed leak check due to `{}`", e
);
2746 debug
!("match_impl: success impl_substs={:?}", impl_substs
);
2749 obligations
: impl_trait_ref
.obligations
2753 fn fast_reject_trait_refs(&mut self,
2754 obligation
: &TraitObligation
,
2755 impl_trait_ref
: &ty
::TraitRef
)
2758 // We can avoid creating type variables and doing the full
2759 // substitution if we find that any of the input types, when
2760 // simplified, do not match.
2762 obligation
.predicate
.skip_binder().input_types()
2763 .zip(impl_trait_ref
.input_types())
2764 .any(|(obligation_ty
, impl_ty
)| {
2765 let simplified_obligation_ty
=
2766 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2767 let simplified_impl_ty
=
2768 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2770 simplified_obligation_ty
.is_some() &&
2771 simplified_impl_ty
.is_some() &&
2772 simplified_obligation_ty
!= simplified_impl_ty
2776 /// Normalize `where_clause_trait_ref` and try to match it against
2777 /// `obligation`. If successful, return any predicates that
2778 /// result from the normalization. Normalization is necessary
2779 /// because where-clauses are stored in the parameter environment
2781 fn match_where_clause_trait_ref(&mut self,
2782 obligation
: &TraitObligation
<'tcx
>,
2783 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2784 -> Result
<Vec
<PredicateObligation
<'tcx
>>,()>
2786 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)?
;
2790 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2791 /// obligation is satisfied.
2792 fn match_poly_trait_ref(&mut self,
2793 obligation
: &TraitObligation
<'tcx
>,
2794 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2797 debug
!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2801 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2802 .sup(obligation
.predicate
.to_poly_trait_ref(), poly_trait_ref
)
2803 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2807 ///////////////////////////////////////////////////////////////////////////
2810 fn match_fresh_trait_refs(&self,
2811 previous
: &ty
::PolyTraitRef
<'tcx
>,
2812 current
: &ty
::PolyTraitRef
<'tcx
>)
2815 let mut matcher
= ty
::_match
::Match
::new(self.tcx());
2816 matcher
.relate(previous
, current
).is_ok()
2819 fn push_stack
<'o
,'s
:'o
>(&mut self,
2820 previous_stack
: TraitObligationStackList
<'s
, 'tcx
>,
2821 obligation
: &'o TraitObligation
<'tcx
>)
2822 -> TraitObligationStack
<'o
, 'tcx
>
2824 let fresh_trait_ref
=
2825 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2827 TraitObligationStack
{
2830 previous
: previous_stack
,
2834 fn closure_trait_ref_unnormalized(&mut self,
2835 obligation
: &TraitObligation
<'tcx
>,
2836 closure_def_id
: DefId
,
2837 substs
: ty
::ClosureSubsts
<'tcx
>)
2838 -> ty
::PolyTraitRef
<'tcx
>
2840 let closure_type
= self.infcx
.fn_sig(closure_def_id
)
2841 .subst(self.tcx(), substs
.substs
);
2842 let ty
::Binder((trait_ref
, _
)) =
2843 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2844 obligation
.predicate
.0.self_ty(), // (1)
2846 util
::TupleArgumentsFlag
::No
);
2847 // (1) Feels icky to skip the binder here, but OTOH we know
2848 // that the self-type is an unboxed closure type and hence is
2849 // in fact unparameterized (or at least does not reference any
2850 // regions bound in the obligation). Still probably some
2851 // refactoring could make this nicer.
2853 ty
::Binder(trait_ref
)
2856 fn closure_trait_ref(&mut self,
2857 obligation
: &TraitObligation
<'tcx
>,
2858 closure_def_id
: DefId
,
2859 substs
: ty
::ClosureSubsts
<'tcx
>)
2860 -> Normalized
<'tcx
, ty
::PolyTraitRef
<'tcx
>>
2862 let trait_ref
= self.closure_trait_ref_unnormalized(
2863 obligation
, closure_def_id
, substs
);
2865 // A closure signature can contain associated types which
2866 // must be normalized.
2867 normalize_with_depth(self,
2868 obligation
.param_env
,
2869 obligation
.cause
.clone(),
2870 obligation
.recursion_depth
+1,
2874 /// Returns the obligations that are implied by instantiating an
2875 /// impl or trait. The obligations are substituted and fully
2876 /// normalized. This is used when confirming an impl or default
2878 fn impl_or_trait_obligations(&mut self,
2879 cause
: ObligationCause
<'tcx
>,
2880 recursion_depth
: usize,
2881 param_env
: ty
::ParamEnv
<'tcx
>,
2882 def_id
: DefId
, // of impl or trait
2883 substs
: &Substs
<'tcx
>, // for impl or trait
2884 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2885 snapshot
: &infer
::CombinedSnapshot
)
2886 -> Vec
<PredicateObligation
<'tcx
>>
2888 debug
!("impl_or_trait_obligations(def_id={:?})", def_id
);
2889 let tcx
= self.tcx();
2891 // To allow for one-pass evaluation of the nested obligation,
2892 // each predicate must be preceded by the obligations required
2894 // for example, if we have:
2895 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2896 // the impl will have the following predicates:
2897 // <V as Iterator>::Item = U,
2898 // U: Iterator, U: Sized,
2899 // V: Iterator, V: Sized,
2900 // <U as Iterator>::Item: Copy
2901 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2902 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2903 // `$1: Copy`, so we must ensure the obligations are emitted in
2905 let predicates
= tcx
.predicates_of(def_id
);
2906 assert_eq
!(predicates
.parent
, None
);
2907 let predicates
= predicates
.predicates
.iter().flat_map(|predicate
| {
2908 let predicate
= normalize_with_depth(self, param_env
, cause
.clone(), recursion_depth
,
2909 &predicate
.subst(tcx
, substs
));
2910 predicate
.obligations
.into_iter().chain(
2912 cause
: cause
.clone(),
2915 predicate
: predicate
.value
2918 self.infcx().plug_leaks(skol_map
, snapshot
, predicates
)
2922 impl<'tcx
> TraitObligation
<'tcx
> {
2923 #[allow(unused_comparisons)]
2924 pub fn derived_cause(&self,
2925 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>)
2926 -> ObligationCause
<'tcx
>
2929 * Creates a cause for obligations that are derived from
2930 * `obligation` by a recursive search (e.g., for a builtin
2931 * bound, or eventually a `impl Foo for ..`). If `obligation`
2932 * is itself a derived obligation, this is just a clone, but
2933 * otherwise we create a "derived obligation" cause so as to
2934 * keep track of the original root obligation for error
2938 let obligation
= self;
2940 // NOTE(flaper87): As of now, it keeps track of the whole error
2941 // chain. Ideally, we should have a way to configure this either
2942 // by using -Z verbose or just a CLI argument.
2943 if obligation
.recursion_depth
>= 0 {
2944 let derived_cause
= DerivedObligationCause
{
2945 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2946 parent_code
: Rc
::new(obligation
.cause
.code
.clone())
2948 let derived_code
= variant(derived_cause
);
2949 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2951 obligation
.cause
.clone()
2956 impl<'tcx
> SelectionCache
<'tcx
> {
2957 pub fn new() -> SelectionCache
<'tcx
> {
2959 hashmap
: RefCell
::new(FxHashMap())
2964 impl<'tcx
> EvaluationCache
<'tcx
> {
2965 pub fn new() -> EvaluationCache
<'tcx
> {
2967 hashmap
: RefCell
::new(FxHashMap())
2972 impl<'o
,'tcx
> TraitObligationStack
<'o
,'tcx
> {
2973 fn list(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2974 TraitObligationStackList
::with(self)
2977 fn iter(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2982 #[derive(Copy, Clone)]
2983 struct TraitObligationStackList
<'o
,'tcx
:'o
> {
2984 head
: Option
<&'o TraitObligationStack
<'o
,'tcx
>>
2987 impl<'o
,'tcx
> TraitObligationStackList
<'o
,'tcx
> {
2988 fn empty() -> TraitObligationStackList
<'o
,'tcx
> {
2989 TraitObligationStackList { head: None }
2992 fn with(r
: &'o TraitObligationStack
<'o
,'tcx
>) -> TraitObligationStackList
<'o
,'tcx
> {
2993 TraitObligationStackList { head: Some(r) }
2997 impl<'o
,'tcx
> Iterator
for TraitObligationStackList
<'o
,'tcx
>{
2998 type Item
= &'o TraitObligationStack
<'o
,'tcx
>;
3000 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
,'tcx
>> {
3011 impl<'o
,'tcx
> fmt
::Debug
for TraitObligationStack
<'o
,'tcx
> {
3012 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
3013 write
!(f
, "TraitObligationStack({:?})", self.obligation
)
3017 impl EvaluationResult
{
3018 fn may_apply(&self) -> bool
{
3022 EvaluatedToUnknown
=> true,
3024 EvaluatedToErr
=> false