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 }
=> {
215 has_nested
: 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();
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 // Check the cache from the tcx of predicates that we know
518 // have been proven elsewhere. This cache only contains
519 // predicates that are global in scope and hence unaffected by
520 // the current environment.
521 if self.tcx().fulfilled_predicates
.borrow().check_duplicate(&obligation
.predicate
) {
522 return EvaluatedToOk
;
525 match obligation
.predicate
{
526 ty
::Predicate
::Trait(ref t
) => {
527 assert
!(!t
.has_escaping_regions());
528 let obligation
= obligation
.with(t
.clone());
529 self.evaluate_obligation_recursively(previous_stack
, &obligation
)
532 ty
::Predicate
::Equate(ref p
) => {
533 // does this code ever run?
534 match self.infcx
.equality_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
535 Ok(InferOk { obligations, .. }
) => {
536 self.inferred_obligations
.extend(obligations
);
539 Err(_
) => EvaluatedToErr
543 ty
::Predicate
::Subtype(ref p
) => {
544 // does this code ever run?
545 match self.infcx
.subtype_predicate(&obligation
.cause
, obligation
.param_env
, p
) {
546 Some(Ok(InferOk { obligations, .. }
)) => {
547 self.inferred_obligations
.extend(obligations
);
550 Some(Err(_
)) => EvaluatedToErr
,
551 None
=> EvaluatedToAmbig
,
555 ty
::Predicate
::WellFormed(ty
) => {
556 match ty
::wf
::obligations(self.infcx
,
557 obligation
.param_env
,
558 obligation
.cause
.body_id
,
559 ty
, obligation
.cause
.span
) {
561 self.evaluate_predicates_recursively(previous_stack
, obligations
.iter()),
567 ty
::Predicate
::TypeOutlives(..) | ty
::Predicate
::RegionOutlives(..) => {
568 // we do not consider region relationships when
569 // evaluating trait matches
573 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
574 if self.tcx().is_object_safe(trait_def_id
) {
581 ty
::Predicate
::Projection(ref data
) => {
582 let project_obligation
= obligation
.with(data
.clone());
583 match project
::poly_project_and_unify_type(self, &project_obligation
) {
584 Ok(Some(subobligations
)) => {
585 self.evaluate_predicates_recursively(previous_stack
,
586 subobligations
.iter())
597 ty
::Predicate
::ClosureKind(closure_def_id
, kind
) => {
598 match self.infcx
.closure_kind(closure_def_id
) {
599 Some(closure_kind
) => {
600 if closure_kind
.extends(kind
) {
614 fn evaluate_obligation_recursively
<'o
>(&mut self,
615 previous_stack
: TraitObligationStackList
<'o
, 'tcx
>,
616 obligation
: &TraitObligation
<'tcx
>)
619 debug
!("evaluate_obligation_recursively({:?})",
622 let stack
= self.push_stack(previous_stack
, obligation
);
623 let fresh_trait_ref
= stack
.fresh_trait_ref
;
624 if let Some(result
) = self.check_evaluation_cache(obligation
.param_env
, fresh_trait_ref
) {
625 debug
!("CACHE HIT: EVAL({:?})={:?}",
631 let result
= self.evaluate_stack(&stack
);
633 debug
!("CACHE MISS: EVAL({:?})={:?}",
636 self.insert_evaluation_cache(obligation
.param_env
, fresh_trait_ref
, result
);
641 fn evaluate_stack
<'o
>(&mut self,
642 stack
: &TraitObligationStack
<'o
, 'tcx
>)
645 // In intercrate mode, whenever any of the types are unbound,
646 // there can always be an impl. Even if there are no impls in
647 // this crate, perhaps the type would be unified with
648 // something from another crate that does provide an impl.
650 // In intra mode, we must still be conservative. The reason is
651 // that we want to avoid cycles. Imagine an impl like:
653 // impl<T:Eq> Eq for Vec<T>
655 // and a trait reference like `$0 : Eq` where `$0` is an
656 // unbound variable. When we evaluate this trait-reference, we
657 // will unify `$0` with `Vec<$1>` (for some fresh variable
658 // `$1`), on the condition that `$1 : Eq`. We will then wind
659 // up with many candidates (since that are other `Eq` impls
660 // that apply) and try to winnow things down. This results in
661 // a recursive evaluation that `$1 : Eq` -- as you can
662 // imagine, this is just where we started. To avoid that, we
663 // check for unbound variables and return an ambiguous (hence possible)
664 // match if we've seen this trait before.
666 // This suffices to allow chains like `FnMut` implemented in
667 // terms of `Fn` etc, but we could probably make this more
669 let unbound_input_types
= stack
.fresh_trait_ref
.input_types().any(|ty
| ty
.is_fresh());
670 if unbound_input_types
&& self.intercrate
{
671 debug
!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
672 stack
.fresh_trait_ref
);
673 return EvaluatedToAmbig
;
675 if unbound_input_types
&&
676 stack
.iter().skip(1).any(
677 |prev
| self.match_fresh_trait_refs(&stack
.fresh_trait_ref
,
678 &prev
.fresh_trait_ref
))
680 debug
!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
681 stack
.fresh_trait_ref
);
682 return EvaluatedToUnknown
;
685 // If there is any previous entry on the stack that precisely
686 // matches this obligation, then we can assume that the
687 // obligation is satisfied for now (still all other conditions
688 // must be met of course). One obvious case this comes up is
689 // marker traits like `Send`. Think of a linked list:
691 // struct List<T> { data: T, next: Option<Box<List<T>>> {
693 // `Box<List<T>>` will be `Send` if `T` is `Send` and
694 // `Option<Box<List<T>>>` is `Send`, and in turn
695 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
698 // Note that we do this comparison using the `fresh_trait_ref`
699 // fields. Because these have all been skolemized using
700 // `self.freshener`, we can be sure that (a) this will not
701 // affect the inferencer state and (b) that if we see two
702 // skolemized types with the same index, they refer to the
703 // same unbound type variable.
706 .skip(1) // skip top-most frame
707 .any(|prev
| stack
.fresh_trait_ref
== prev
.fresh_trait_ref
)
709 debug
!("evaluate_stack({:?}) --> recursive",
710 stack
.fresh_trait_ref
);
711 return EvaluatedToOk
;
714 match self.candidate_from_obligation(stack
) {
715 Ok(Some(c
)) => self.evaluate_candidate(stack
, &c
),
716 Ok(None
) => EvaluatedToAmbig
,
717 Err(..) => EvaluatedToErr
721 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
722 /// obligations are met. Returns true if `candidate` remains viable after this further
724 fn evaluate_candidate
<'o
>(&mut self,
725 stack
: &TraitObligationStack
<'o
, 'tcx
>,
726 candidate
: &SelectionCandidate
<'tcx
>)
729 debug
!("evaluate_candidate: depth={} candidate={:?}",
730 stack
.obligation
.recursion_depth
, candidate
);
731 let result
= self.probe(|this
, _
| {
732 let candidate
= (*candidate
).clone();
733 match this
.confirm_candidate(stack
.obligation
, candidate
) {
735 this
.evaluate_predicates_recursively(
737 selection
.nested_obligations().iter())
739 Err(..) => EvaluatedToErr
742 debug
!("evaluate_candidate: depth={} result={:?}",
743 stack
.obligation
.recursion_depth
, result
);
747 fn check_evaluation_cache(&self,
748 param_env
: ty
::ParamEnv
<'tcx
>,
749 trait_ref
: ty
::PolyTraitRef
<'tcx
>)
750 -> Option
<EvaluationResult
>
752 if self.can_use_global_caches(param_env
) {
753 let cache
= self.tcx().evaluation_cache
.hashmap
.borrow();
754 if let Some(cached
) = cache
.get(&trait_ref
) {
755 return Some(cached
.clone());
758 self.infcx
.evaluation_cache
.hashmap
.borrow().get(&trait_ref
).cloned()
761 fn insert_evaluation_cache(&mut self,
762 param_env
: ty
::ParamEnv
<'tcx
>,
763 trait_ref
: ty
::PolyTraitRef
<'tcx
>,
764 result
: EvaluationResult
)
766 // Avoid caching results that depend on more than just the trait-ref:
767 // The stack can create EvaluatedToUnknown, and closure signatures
768 // being yet uninferred can create "spurious" EvaluatedToAmbig
769 // and EvaluatedToOk.
770 if result
== EvaluatedToUnknown
||
771 ((result
== EvaluatedToAmbig
|| result
== EvaluatedToOk
)
772 && trait_ref
.has_closure_types())
777 if self.can_use_global_caches(param_env
) {
778 let mut cache
= self.tcx().evaluation_cache
.hashmap
.borrow_mut();
779 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
780 cache
.insert(trait_ref
, result
);
785 self.infcx
.evaluation_cache
.hashmap
.borrow_mut().insert(trait_ref
, result
);
788 ///////////////////////////////////////////////////////////////////////////
789 // CANDIDATE ASSEMBLY
791 // The selection process begins by examining all in-scope impls,
792 // caller obligations, and so forth and assembling a list of
793 // candidates. See `README.md` and the `Candidate` type for more
796 fn candidate_from_obligation
<'o
>(&mut self,
797 stack
: &TraitObligationStack
<'o
, 'tcx
>)
798 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
800 // Watch out for overflow. This intentionally bypasses (and does
801 // not update) the cache.
802 let recursion_limit
= self.infcx
.tcx
.sess
.recursion_limit
.get();
803 if stack
.obligation
.recursion_depth
>= recursion_limit
{
804 self.infcx().report_overflow_error(&stack
.obligation
, true);
807 // Check the cache. Note that we skolemize the trait-ref
808 // separately rather than using `stack.fresh_trait_ref` -- this
809 // is because we want the unbound variables to be replaced
810 // with fresh skolemized types starting from index 0.
811 let cache_fresh_trait_pred
=
812 self.infcx
.freshen(stack
.obligation
.predicate
.clone());
813 debug
!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
814 cache_fresh_trait_pred
,
816 assert
!(!stack
.obligation
.predicate
.has_escaping_regions());
818 if let Some(c
) = self.check_candidate_cache(stack
.obligation
.param_env
,
819 &cache_fresh_trait_pred
) {
820 debug
!("CACHE HIT: SELECT({:?})={:?}",
821 cache_fresh_trait_pred
,
826 // If no match, compute result and insert into cache.
827 let candidate
= self.candidate_from_obligation_no_cache(stack
);
829 if self.should_update_candidate_cache(&cache_fresh_trait_pred
, &candidate
) {
830 debug
!("CACHE MISS: SELECT({:?})={:?}",
831 cache_fresh_trait_pred
, candidate
);
832 self.insert_candidate_cache(stack
.obligation
.param_env
,
833 cache_fresh_trait_pred
,
840 // Treat negative impls as unimplemented
841 fn filter_negative_impls(&self, candidate
: SelectionCandidate
<'tcx
>)
842 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>> {
843 if let ImplCandidate(def_id
) = candidate
{
844 if self.tcx().impl_polarity(def_id
) == hir
::ImplPolarity
::Negative
{
845 return Err(Unimplemented
)
851 fn candidate_from_obligation_no_cache
<'o
>(&mut self,
852 stack
: &TraitObligationStack
<'o
, 'tcx
>)
853 -> SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>
855 if stack
.obligation
.predicate
.references_error() {
856 // If we encounter a `TyError`, we generally prefer the
857 // most "optimistic" result in response -- that is, the
858 // one least likely to report downstream errors. But
859 // because this routine is shared by coherence and by
860 // trait selection, there isn't an obvious "right" choice
861 // here in that respect, so we opt to just return
862 // ambiguity and let the upstream clients sort it out.
866 if !self.is_knowable(stack
) {
867 debug
!("coherence stage: not knowable");
871 let candidate_set
= self.assemble_candidates(stack
)?
;
873 if candidate_set
.ambiguous
{
874 debug
!("candidate set contains ambig");
878 let mut candidates
= candidate_set
.vec
;
880 debug
!("assembled {} candidates for {:?}: {:?}",
885 // At this point, we know that each of the entries in the
886 // candidate set is *individually* applicable. Now we have to
887 // figure out if they contain mutual incompatibilities. This
888 // frequently arises if we have an unconstrained input type --
889 // for example, we are looking for $0:Eq where $0 is some
890 // unconstrained type variable. In that case, we'll get a
891 // candidate which assumes $0 == int, one that assumes $0 ==
892 // usize, etc. This spells an ambiguity.
894 // If there is more than one candidate, first winnow them down
895 // by considering extra conditions (nested obligations and so
896 // forth). We don't winnow if there is exactly one
897 // candidate. This is a relatively minor distinction but it
898 // can lead to better inference and error-reporting. An
899 // example would be if there was an impl:
901 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
903 // and we were to see some code `foo.push_clone()` where `boo`
904 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
905 // we were to winnow, we'd wind up with zero candidates.
906 // Instead, we select the right impl now but report `Bar does
907 // not implement Clone`.
908 if candidates
.len() == 1 {
909 return self.filter_negative_impls(candidates
.pop().unwrap());
912 // Winnow, but record the exact outcome of evaluation, which
913 // is needed for specialization.
914 let mut candidates
: Vec
<_
> = candidates
.into_iter().filter_map(|c
| {
915 let eval
= self.evaluate_candidate(stack
, &c
);
916 if eval
.may_apply() {
917 Some(EvaluatedCandidate
{
926 // If there are STILL multiple candidate, we can further
927 // reduce the list by dropping duplicates -- including
928 // resolving specializations.
929 if candidates
.len() > 1 {
931 while i
< candidates
.len() {
933 (0..candidates
.len())
935 .any(|j
| self.candidate_should_be_dropped_in_favor_of(&candidates
[i
],
938 debug
!("Dropping candidate #{}/{}: {:?}",
939 i
, candidates
.len(), candidates
[i
]);
940 candidates
.swap_remove(i
);
942 debug
!("Retaining candidate #{}/{}: {:?}",
943 i
, candidates
.len(), candidates
[i
]);
946 // If there are *STILL* multiple candidates, give up
947 // and report ambiguity.
949 debug
!("multiple matches, ambig");
956 // If there are *NO* candidates, then there are no impls --
957 // that we know of, anyway. Note that in the case where there
958 // are unbound type variables within the obligation, it might
959 // be the case that you could still satisfy the obligation
960 // from another crate by instantiating the type variables with
961 // a type from another crate that does have an impl. This case
962 // is checked for in `evaluate_stack` (and hence users
963 // who might care about this case, like coherence, should use
965 if candidates
.is_empty() {
966 return Err(Unimplemented
);
969 // Just one candidate left.
970 self.filter_negative_impls(candidates
.pop().unwrap().candidate
)
973 fn is_knowable
<'o
>(&mut self,
974 stack
: &TraitObligationStack
<'o
, 'tcx
>)
977 debug
!("is_knowable(intercrate={})", self.intercrate
);
979 if !self.intercrate
{
983 let obligation
= &stack
.obligation
;
984 let predicate
= self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
986 // ok to skip binder because of the nature of the
987 // trait-ref-is-knowable check, which does not care about
989 let trait_ref
= &predicate
.skip_binder().trait_ref
;
991 coherence
::trait_ref_is_knowable(self.tcx(), trait_ref
)
994 /// Returns true if the global caches can be used.
995 /// Do note that if the type itself is not in the
996 /// global tcx, the local caches will be used.
997 fn can_use_global_caches(&self, param_env
: ty
::ParamEnv
<'tcx
>) -> bool
{
998 // If there are any where-clauses in scope, then we always use
999 // a cache local to this particular scope. Otherwise, we
1000 // switch to a global cache. We used to try and draw
1001 // finer-grained distinctions, but that led to a serious of
1002 // annoying and weird bugs like #22019 and #18290. This simple
1003 // rule seems to be pretty clearly safe and also still retains
1004 // a very high hit rate (~95% when compiling rustc).
1005 if !param_env
.caller_bounds
.is_empty() {
1009 // Avoid using the master cache during coherence and just rely
1010 // on the local cache. This effectively disables caching
1011 // during coherence. It is really just a simplification to
1012 // avoid us having to fear that coherence results "pollute"
1013 // the master cache. Since coherence executes pretty quickly,
1014 // it's not worth going to more trouble to increase the
1015 // hit-rate I don't think.
1016 if self.intercrate
{
1020 // Otherwise, we can use the global cache.
1024 fn check_candidate_cache(&mut self,
1025 param_env
: ty
::ParamEnv
<'tcx
>,
1026 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>)
1027 -> Option
<SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>>
1029 let trait_ref
= &cache_fresh_trait_pred
.0.trait_ref
;
1030 if self.can_use_global_caches(param_env
) {
1031 let cache
= self.tcx().selection_cache
.hashmap
.borrow();
1032 if let Some(cached
) = cache
.get(&trait_ref
) {
1033 return Some(cached
.clone());
1036 self.infcx
.selection_cache
.hashmap
.borrow().get(trait_ref
).cloned()
1039 fn insert_candidate_cache(&mut self,
1040 param_env
: ty
::ParamEnv
<'tcx
>,
1041 cache_fresh_trait_pred
: ty
::PolyTraitPredicate
<'tcx
>,
1042 candidate
: SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1044 let trait_ref
= cache_fresh_trait_pred
.0.trait_ref
;
1045 if self.can_use_global_caches(param_env
) {
1046 let mut cache
= self.tcx().selection_cache
.hashmap
.borrow_mut();
1047 if let Some(trait_ref
) = self.tcx().lift_to_global(&trait_ref
) {
1048 if let Some(candidate
) = self.tcx().lift_to_global(&candidate
) {
1049 cache
.insert(trait_ref
, candidate
);
1055 self.infcx
.selection_cache
.hashmap
.borrow_mut().insert(trait_ref
, candidate
);
1058 fn should_update_candidate_cache(&mut self,
1059 cache_fresh_trait_pred
: &ty
::PolyTraitPredicate
<'tcx
>,
1060 candidate
: &SelectionResult
<'tcx
, SelectionCandidate
<'tcx
>>)
1063 // In general, it's a good idea to cache results, even
1064 // ambiguous ones, to save us some trouble later. But we have
1065 // to be careful not to cache results that could be
1066 // invalidated later by advances in inference. Normally, this
1067 // is not an issue, because any inference variables whose
1068 // types are not yet bound are "freshened" in the cache key,
1069 // which means that if we later get the same request once that
1070 // type variable IS bound, we'll have a different cache key.
1071 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
1072 // not yet known, we may cache the result as `None`. But if
1073 // later `_#0t` is bound to `Bar`, then when we freshen we'll
1074 // have `Vec<Bar> : Foo` as the cache key.
1076 // HOWEVER, it CAN happen that we get an ambiguity result in
1077 // one particular case around closures where the cache key
1078 // would not change. That is when the precise types of the
1079 // upvars that a closure references have not yet been figured
1080 // out (i.e., because it is not yet known if they are captured
1081 // by ref, and if by ref, what kind of ref). In these cases,
1082 // when matching a builtin bound, we will yield back an
1083 // ambiguous result. But the *cache key* is just the closure type,
1084 // it doesn't capture the state of the upvar computation.
1086 // To avoid this trap, just don't cache ambiguous results if
1087 // the self-type contains no inference byproducts (that really
1088 // shouldn't happen in other circumstances anyway, given
1092 Ok(Some(_
)) | Err(_
) => true,
1093 Ok(None
) => cache_fresh_trait_pred
.has_infer_types()
1097 fn assemble_candidates
<'o
>(&mut self,
1098 stack
: &TraitObligationStack
<'o
, 'tcx
>)
1099 -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>>
1101 let TraitObligationStack { obligation, .. }
= *stack
;
1102 let ref obligation
= Obligation
{
1103 param_env
: obligation
.param_env
,
1104 cause
: obligation
.cause
.clone(),
1105 recursion_depth
: obligation
.recursion_depth
,
1106 predicate
: self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
)
1109 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
1110 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1112 // This is somewhat problematic, as the current scheme can't really
1113 // handle it turning to be a projection. This does end up as truly
1114 // ambiguous in most cases anyway.
1116 // Until this is fixed, take the fast path out - this also improves
1117 // performance by preventing assemble_candidates_from_impls from
1118 // matching every impl for this trait.
1119 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
1122 let mut candidates
= SelectionCandidateSet
{
1127 // Other bounds. Consider both in-scope bounds from fn decl
1128 // and applicable impls. There is a certain set of precedence rules here.
1130 let def_id
= obligation
.predicate
.def_id();
1131 if self.tcx().lang_items
.copy_trait() == Some(def_id
) {
1132 debug
!("obligation self ty is {:?}",
1133 obligation
.predicate
.0.self_ty());
1135 // User-defined copy impls are permitted, but only for
1136 // structs and enums.
1137 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1139 // For other types, we'll use the builtin rules.
1140 let copy_conditions
= self.copy_conditions(obligation
);
1141 self.assemble_builtin_bound_candidates(copy_conditions
, &mut candidates
)?
;
1142 } else if self.tcx().lang_items
.sized_trait() == Some(def_id
) {
1143 // Sized is never implementable by end-users, it is
1144 // always automatically computed.
1145 let sized_conditions
= self.sized_conditions(obligation
);
1146 self.assemble_builtin_bound_candidates(sized_conditions
,
1148 } else if self.tcx().lang_items
.unsize_trait() == Some(def_id
) {
1149 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
1151 self.assemble_closure_candidates(obligation
, &mut candidates
)?
;
1152 self.assemble_fn_pointer_candidates(obligation
, &mut candidates
)?
;
1153 self.assemble_candidates_from_impls(obligation
, &mut candidates
)?
;
1154 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
1157 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
1158 self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
)?
;
1159 // Default implementations have lower priority, so we only
1160 // consider triggering a default if there is no other impl that can apply.
1161 if candidates
.vec
.is_empty() {
1162 self.assemble_candidates_from_default_impls(obligation
, &mut candidates
)?
;
1164 debug
!("candidate list size: {}", candidates
.vec
.len());
1168 fn assemble_candidates_from_projected_tys(&mut self,
1169 obligation
: &TraitObligation
<'tcx
>,
1170 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1172 debug
!("assemble_candidates_for_projected_tys({:?})", obligation
);
1174 // FIXME(#20297) -- just examining the self-type is very simplistic
1176 // before we go into the whole skolemization thing, just
1177 // quickly check if the self-type is a projection at all.
1178 match obligation
.predicate
.0.trait_ref
.self_ty().sty
{
1179 ty
::TyProjection(_
) | ty
::TyAnon(..) => {}
1180 ty
::TyInfer(ty
::TyVar(_
)) => {
1181 span_bug
!(obligation
.cause
.span
,
1182 "Self=_ should have been handled by assemble_candidates");
1187 let result
= self.probe(|this
, snapshot
| {
1188 this
.match_projection_obligation_against_definition_bounds(obligation
,
1193 candidates
.vec
.push(ProjectionCandidate
);
1197 fn match_projection_obligation_against_definition_bounds(
1199 obligation
: &TraitObligation
<'tcx
>,
1200 snapshot
: &infer
::CombinedSnapshot
)
1203 let poly_trait_predicate
=
1204 self.infcx().resolve_type_vars_if_possible(&obligation
.predicate
);
1205 let (skol_trait_predicate
, skol_map
) =
1206 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate
, snapshot
);
1207 debug
!("match_projection_obligation_against_definition_bounds: \
1208 skol_trait_predicate={:?} skol_map={:?}",
1209 skol_trait_predicate
,
1212 let (def_id
, substs
) = match skol_trait_predicate
.trait_ref
.self_ty().sty
{
1213 ty
::TyProjection(ref data
) => (data
.trait_ref
.def_id
, data
.trait_ref
.substs
),
1214 ty
::TyAnon(def_id
, substs
) => (def_id
, substs
),
1217 obligation
.cause
.span
,
1218 "match_projection_obligation_against_definition_bounds() called \
1219 but self-ty not a projection: {:?}",
1220 skol_trait_predicate
.trait_ref
.self_ty());
1223 debug
!("match_projection_obligation_against_definition_bounds: \
1224 def_id={:?}, substs={:?}",
1227 let predicates_of
= self.tcx().predicates_of(def_id
);
1228 let bounds
= predicates_of
.instantiate(self.tcx(), substs
);
1229 debug
!("match_projection_obligation_against_definition_bounds: \
1233 let matching_bound
=
1234 util
::elaborate_predicates(self.tcx(), bounds
.predicates
)
1238 |this
, _
| this
.match_projection(obligation
,
1240 skol_trait_predicate
.trait_ref
.clone(),
1244 debug
!("match_projection_obligation_against_definition_bounds: \
1245 matching_bound={:?}",
1247 match matching_bound
{
1250 // Repeat the successful match, if any, this time outside of a probe.
1251 let result
= self.match_projection(obligation
,
1253 skol_trait_predicate
.trait_ref
.clone(),
1257 self.infcx
.pop_skolemized(skol_map
, snapshot
);
1265 fn match_projection(&mut self,
1266 obligation
: &TraitObligation
<'tcx
>,
1267 trait_bound
: ty
::PolyTraitRef
<'tcx
>,
1268 skol_trait_ref
: ty
::TraitRef
<'tcx
>,
1269 skol_map
: &infer
::SkolemizationMap
<'tcx
>,
1270 snapshot
: &infer
::CombinedSnapshot
)
1273 assert
!(!skol_trait_ref
.has_escaping_regions());
1274 match self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
1275 .sup(ty
::Binder(skol_trait_ref
), trait_bound
) {
1276 Ok(InferOk { obligations, .. }
) => {
1277 self.inferred_obligations
.extend(obligations
);
1279 Err(_
) => { return false; }
1282 self.infcx
.leak_check(false, obligation
.cause
.span
, skol_map
, snapshot
).is_ok()
1285 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1286 /// supplied to find out whether it is listed among them.
1288 /// Never affects inference environment.
1289 fn assemble_candidates_from_caller_bounds
<'o
>(&mut self,
1290 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1291 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1292 -> Result
<(),SelectionError
<'tcx
>>
1294 debug
!("assemble_candidates_from_caller_bounds({:?})",
1298 stack
.obligation
.param_env
.caller_bounds
1300 .filter_map(|o
| o
.to_opt_poly_trait_ref());
1302 // micro-optimization: filter out predicates relating to different
1304 let matching_bounds
=
1305 all_bounds
.filter(|p
| p
.def_id() == stack
.obligation
.predicate
.def_id());
1307 let matching_bounds
=
1308 matching_bounds
.filter(
1309 |bound
| self.evaluate_where_clause(stack
, bound
.clone()).may_apply());
1311 let param_candidates
=
1312 matching_bounds
.map(|bound
| ParamCandidate(bound
));
1314 candidates
.vec
.extend(param_candidates
);
1319 fn evaluate_where_clause
<'o
>(&mut self,
1320 stack
: &TraitObligationStack
<'o
, 'tcx
>,
1321 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
1324 self.probe(move |this
, _
| {
1325 match this
.match_where_clause_trait_ref(stack
.obligation
, where_clause_trait_ref
) {
1326 Ok(obligations
) => {
1327 this
.evaluate_predicates_recursively(stack
.list(), obligations
.iter())
1329 Err(()) => EvaluatedToErr
1334 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1335 /// FnMut<..>` where `X` is a closure type.
1337 /// Note: the type parameters on a closure candidate are modeled as *output* type
1338 /// parameters and hence do not affect whether this trait is a match or not. They will be
1339 /// unified during the confirmation step.
1340 fn assemble_closure_candidates(&mut self,
1341 obligation
: &TraitObligation
<'tcx
>,
1342 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1343 -> Result
<(),SelectionError
<'tcx
>>
1345 let kind
= match self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.0.def_id()) {
1347 None
=> { return Ok(()); }
1350 // ok to skip binder because the substs on closure types never
1351 // touch bound regions, they just capture the in-scope
1352 // type/region parameters
1353 let self_ty
= *obligation
.self_ty().skip_binder();
1354 let (closure_def_id
, substs
) = match self_ty
.sty
{
1355 ty
::TyClosure(id
, substs
) => (id
, substs
),
1356 ty
::TyInfer(ty
::TyVar(_
)) => {
1357 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
1358 candidates
.ambiguous
= true;
1361 _
=> { return Ok(()); }
1364 debug
!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1369 match self.infcx
.closure_kind(closure_def_id
) {
1370 Some(closure_kind
) => {
1371 debug
!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind
);
1372 if closure_kind
.extends(kind
) {
1373 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1377 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
1378 candidates
.vec
.push(ClosureCandidate(closure_def_id
, substs
, kind
));
1385 /// Implement one of the `Fn()` family for a fn pointer.
1386 fn assemble_fn_pointer_candidates(&mut self,
1387 obligation
: &TraitObligation
<'tcx
>,
1388 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1389 -> Result
<(),SelectionError
<'tcx
>>
1391 // We provide impl of all fn traits for fn pointers.
1392 if self.tcx().lang_items
.fn_trait_kind(obligation
.predicate
.def_id()).is_none() {
1396 // ok to skip binder because what we are inspecting doesn't involve bound regions
1397 let self_ty
= *obligation
.self_ty().skip_binder();
1399 ty
::TyInfer(ty
::TyVar(_
)) => {
1400 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
1401 candidates
.ambiguous
= true; // could wind up being a fn() type
1404 // provide an impl, but only for suitable `fn` pointers
1405 ty
::TyFnDef(.., ty
::Binder(ty
::FnSig
{
1406 unsafety
: hir
::Unsafety
::Normal
,
1411 ty
::TyFnPtr(ty
::Binder(ty
::FnSig
{
1412 unsafety
: hir
::Unsafety
::Normal
,
1417 candidates
.vec
.push(FnPointerCandidate
);
1426 /// Search for impls that might apply to `obligation`.
1427 fn assemble_candidates_from_impls(&mut self,
1428 obligation
: &TraitObligation
<'tcx
>,
1429 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1430 -> Result
<(), SelectionError
<'tcx
>>
1432 debug
!("assemble_candidates_from_impls(obligation={:?})", obligation
);
1434 let def
= self.tcx().trait_def(obligation
.predicate
.def_id());
1436 def
.for_each_relevant_impl(
1438 obligation
.predicate
.0.trait_ref
.self_ty(),
1440 self.probe(|this
, snapshot
| { /* [1] */
1441 match this
.match_impl(impl_def_id
, obligation
, snapshot
) {
1443 candidates
.vec
.push(ImplCandidate(impl_def_id
));
1445 // NB: we can safely drop the skol map
1446 // since we are in a probe [1]
1447 mem
::drop(skol_map
);
1458 fn assemble_candidates_from_default_impls(&mut self,
1459 obligation
: &TraitObligation
<'tcx
>,
1460 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1461 -> Result
<(), SelectionError
<'tcx
>>
1463 // OK to skip binder here because the tests we do below do not involve bound regions
1464 let self_ty
= *obligation
.self_ty().skip_binder();
1465 debug
!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty
);
1467 let def_id
= obligation
.predicate
.def_id();
1469 if self.tcx().trait_has_default_impl(def_id
) {
1471 ty
::TyDynamic(..) => {
1472 // For object types, we don't know what the closed
1473 // over types are. This means we conservatively
1474 // say nothing; a candidate may be added by
1475 // `assemble_candidates_from_object_ty`.
1478 ty
::TyProjection(..) => {
1479 // In these cases, we don't know what the actual
1480 // type is. Therefore, we cannot break it down
1481 // into its constituent types. So we don't
1482 // consider the `..` impl but instead just add no
1483 // candidates: this means that typeck will only
1484 // succeed if there is another reason to believe
1485 // that this obligation holds. That could be a
1486 // where-clause or, in the case of an object type,
1487 // it could be that the object type lists the
1488 // trait (e.g. `Foo+Send : Send`). See
1489 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1490 // for an example of a test case that exercises
1493 ty
::TyInfer(ty
::TyVar(_
)) => {
1494 // the defaulted impl might apply, we don't know
1495 candidates
.ambiguous
= true;
1498 candidates
.vec
.push(DefaultImplCandidate(def_id
.clone()))
1506 /// Search for impls that might apply to `obligation`.
1507 fn assemble_candidates_from_object_ty(&mut self,
1508 obligation
: &TraitObligation
<'tcx
>,
1509 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1511 debug
!("assemble_candidates_from_object_ty(self_ty={:?})",
1512 obligation
.self_ty().skip_binder());
1514 // Object-safety candidates are only applicable to object-safe
1515 // traits. Including this check is useful because it helps
1516 // inference in cases of traits like `BorrowFrom`, which are
1517 // not object-safe, and which rely on being able to infer the
1518 // self-type from one of the other inputs. Without this check,
1519 // these cases wind up being considered ambiguous due to a
1520 // (spurious) ambiguity introduced here.
1521 let predicate_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
1522 if !self.tcx().is_object_safe(predicate_trait_ref
.def_id()) {
1526 self.probe(|this
, _snapshot
| {
1527 // the code below doesn't care about regions, and the
1528 // self-ty here doesn't escape this probe, so just erase
1530 let self_ty
= this
.tcx().erase_late_bound_regions(&obligation
.self_ty());
1531 let poly_trait_ref
= match self_ty
.sty
{
1532 ty
::TyDynamic(ref data
, ..) => {
1533 if data
.auto_traits().any(|did
| did
== obligation
.predicate
.def_id()) {
1534 debug
!("assemble_candidates_from_object_ty: matched builtin bound, \
1535 pushing candidate");
1536 candidates
.vec
.push(BuiltinObjectCandidate
);
1540 match data
.principal() {
1541 Some(p
) => p
.with_self_ty(this
.tcx(), self_ty
),
1545 ty
::TyInfer(ty
::TyVar(_
)) => {
1546 debug
!("assemble_candidates_from_object_ty: ambiguous");
1547 candidates
.ambiguous
= true; // could wind up being an object type
1555 debug
!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1558 // Count only those upcast versions that match the trait-ref
1559 // we are looking for. Specifically, do not only check for the
1560 // correct trait, but also the correct type parameters.
1561 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1562 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1563 let upcast_trait_refs
=
1564 util
::supertraits(this
.tcx(), poly_trait_ref
)
1565 .filter(|upcast_trait_ref
| {
1566 this
.probe(|this
, _
| {
1567 let upcast_trait_ref
= upcast_trait_ref
.clone();
1568 this
.match_poly_trait_ref(obligation
, upcast_trait_ref
).is_ok()
1573 if upcast_trait_refs
> 1 {
1574 // can be upcast in many ways; need more type information
1575 candidates
.ambiguous
= true;
1576 } else if upcast_trait_refs
== 1 {
1577 candidates
.vec
.push(ObjectCandidate
);
1582 /// Search for unsizing that might apply to `obligation`.
1583 fn assemble_candidates_for_unsizing(&mut self,
1584 obligation
: &TraitObligation
<'tcx
>,
1585 candidates
: &mut SelectionCandidateSet
<'tcx
>) {
1586 // We currently never consider higher-ranked obligations e.g.
1587 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1588 // because they are a priori invalid, and we could potentially add support
1589 // for them later, it's just that there isn't really a strong need for it.
1590 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1591 // impl, and those are generally applied to concrete types.
1593 // That said, one might try to write a fn with a where clause like
1594 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1595 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1596 // Still, you'd be more likely to write that where clause as
1598 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1599 // obligation above. Should be possible to extend this in the future.
1600 let source
= match self.tcx().no_late_bound_regions(&obligation
.self_ty()) {
1603 // Don't add any candidates if there are bound regions.
1607 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
1609 debug
!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1612 let may_apply
= match (&source
.sty
, &target
.sty
) {
1613 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1614 (&ty
::TyDynamic(ref data_a
, ..), &ty
::TyDynamic(ref data_b
, ..)) => {
1615 // Upcasts permit two things:
1617 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1618 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1620 // Note that neither of these changes requires any
1621 // change at runtime. Eventually this will be
1624 // We always upcast when we can because of reason
1625 // #2 (region bounds).
1626 match (data_a
.principal(), data_b
.principal()) {
1627 (Some(a
), Some(b
)) => a
.def_id() == b
.def_id() &&
1628 data_b
.auto_traits()
1629 // All of a's auto traits need to be in b's auto traits.
1630 .all(|b
| data_a
.auto_traits().any(|a
| a
== b
)),
1636 (_
, &ty
::TyDynamic(..)) => true,
1638 // Ambiguous handling is below T -> Trait, because inference
1639 // variables can still implement Unsize<Trait> and nested
1640 // obligations will have the final say (likely deferred).
1641 (&ty
::TyInfer(ty
::TyVar(_
)), _
) |
1642 (_
, &ty
::TyInfer(ty
::TyVar(_
))) => {
1643 debug
!("assemble_candidates_for_unsizing: ambiguous");
1644 candidates
.ambiguous
= true;
1649 (&ty
::TyArray(..), &ty
::TySlice(_
)) => true,
1651 // Struct<T> -> Struct<U>.
1652 (&ty
::TyAdt(def_id_a
, _
), &ty
::TyAdt(def_id_b
, _
)) if def_id_a
.is_struct() => {
1653 def_id_a
== def_id_b
1660 candidates
.vec
.push(BuiltinUnsizeCandidate
);
1664 ///////////////////////////////////////////////////////////////////////////
1667 // Winnowing is the process of attempting to resolve ambiguity by
1668 // probing further. During the winnowing process, we unify all
1669 // type variables (ignoring skolemization) and then we also
1670 // attempt to evaluate recursive bounds to see if they are
1673 /// Returns true if `candidate_i` should be dropped in favor of
1674 /// `candidate_j`. Generally speaking we will drop duplicate
1675 /// candidates and prefer where-clause candidates.
1676 /// Returns true if `victim` should be dropped in favor of
1677 /// `other`. Generally speaking we will drop duplicate
1678 /// candidates and prefer where-clause candidates.
1680 /// See the comment for "SelectionCandidate" for more details.
1681 fn candidate_should_be_dropped_in_favor_of
<'o
>(
1683 victim
: &EvaluatedCandidate
<'tcx
>,
1684 other
: &EvaluatedCandidate
<'tcx
>)
1687 if victim
.candidate
== other
.candidate
{
1691 match other
.candidate
{
1693 ParamCandidate(_
) | ProjectionCandidate
=> match victim
.candidate
{
1694 DefaultImplCandidate(..) => {
1696 "default implementations shouldn't be recorded \
1697 when there are other valid candidates");
1700 ClosureCandidate(..) |
1701 FnPointerCandidate
|
1702 BuiltinObjectCandidate
|
1703 BuiltinUnsizeCandidate
|
1704 BuiltinCandidate { .. }
=> {
1705 // We have a where-clause so don't go around looking
1710 ProjectionCandidate
=> {
1711 // Arbitrarily give param candidates priority
1712 // over projection and object candidates.
1715 ParamCandidate(..) => false,
1717 ImplCandidate(other_def
) => {
1718 // See if we can toss out `victim` based on specialization.
1719 // This requires us to know *for sure* that the `other` impl applies
1720 // i.e. EvaluatedToOk:
1721 if other
.evaluation
== EvaluatedToOk
{
1722 if let ImplCandidate(victim_def
) = victim
.candidate
{
1723 let tcx
= self.tcx().global_tcx();
1724 return traits
::specializes(tcx
, other_def
, victim_def
) ||
1725 tcx
.impls_are_allowed_to_overlap(other_def
, victim_def
);
1735 ///////////////////////////////////////////////////////////////////////////
1738 // These cover the traits that are built-in to the language
1739 // itself. This includes `Copy` and `Sized` for sure. For the
1740 // moment, it also includes `Send` / `Sync` and a few others, but
1741 // those will hopefully change to library-defined traits in the
1744 // HACK: if this returns an error, selection exits without considering
1746 fn assemble_builtin_bound_candidates
<'o
>(&mut self,
1747 conditions
: BuiltinImplConditions
<'tcx
>,
1748 candidates
: &mut SelectionCandidateSet
<'tcx
>)
1749 -> Result
<(),SelectionError
<'tcx
>>
1752 BuiltinImplConditions
::Where(nested
) => {
1753 debug
!("builtin_bound: nested={:?}", nested
);
1754 candidates
.vec
.push(BuiltinCandidate
{
1755 has_nested
: nested
.skip_binder().len() > 0
1759 BuiltinImplConditions
::None
=> { Ok(()) }
1760 BuiltinImplConditions
::Ambiguous
=> {
1761 debug
!("assemble_builtin_bound_candidates: ambiguous builtin");
1762 Ok(candidates
.ambiguous
= true)
1764 BuiltinImplConditions
::Never
=> { Err(Unimplemented) }
1768 fn sized_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1769 -> BuiltinImplConditions
<'tcx
>
1771 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1773 // NOTE: binder moved to (*)
1774 let self_ty
= self.infcx
.shallow_resolve(
1775 obligation
.predicate
.skip_binder().self_ty());
1778 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1779 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1780 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyRawPtr(..) |
1781 ty
::TyChar
| ty
::TyRef(..) |
1782 ty
::TyArray(..) | ty
::TyClosure(..) | ty
::TyNever
|
1784 // safe for everything
1785 Where(ty
::Binder(Vec
::new()))
1788 ty
::TyStr
| ty
::TySlice(_
) | ty
::TyDynamic(..) => Never
,
1790 ty
::TyTuple(tys
, _
) => {
1791 Where(ty
::Binder(tys
.last().into_iter().cloned().collect()))
1794 ty
::TyAdt(def
, substs
) => {
1795 let sized_crit
= def
.sized_constraint(self.tcx());
1796 // (*) binder moved here
1798 sized_crit
.iter().map(|ty
| ty
.subst(self.tcx(), substs
)).collect()
1802 ty
::TyProjection(_
) | ty
::TyParam(_
) | ty
::TyAnon(..) => None
,
1803 ty
::TyInfer(ty
::TyVar(_
)) => Ambiguous
,
1805 ty
::TyInfer(ty
::FreshTy(_
))
1806 | ty
::TyInfer(ty
::FreshIntTy(_
))
1807 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1808 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1814 fn copy_conditions(&mut self, obligation
: &TraitObligation
<'tcx
>)
1815 -> BuiltinImplConditions
<'tcx
>
1817 // NOTE: binder moved to (*)
1818 let self_ty
= self.infcx
.shallow_resolve(
1819 obligation
.predicate
.skip_binder().self_ty());
1821 use self::BuiltinImplConditions
::{Ambiguous, None, Never, Where}
;
1824 ty
::TyInfer(ty
::IntVar(_
)) | ty
::TyInfer(ty
::FloatVar(_
)) |
1825 ty
::TyUint(_
) | ty
::TyInt(_
) | ty
::TyBool
| ty
::TyFloat(_
) |
1826 ty
::TyFnDef(..) | ty
::TyFnPtr(_
) | ty
::TyChar
|
1827 ty
::TyRawPtr(..) | ty
::TyError
| ty
::TyNever
|
1828 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutImmutable }
) => {
1829 Where(ty
::Binder(Vec
::new()))
1832 ty
::TyDynamic(..) | ty
::TyStr
| ty
::TySlice(..) |
1834 ty
::TyRef(_
, ty
::TypeAndMut { ty: _, mutbl: hir::MutMutable }
) => {
1838 ty
::TyArray(element_ty
, _
) => {
1839 // (*) binder moved here
1840 Where(ty
::Binder(vec
![element_ty
]))
1843 ty
::TyTuple(tys
, _
) => {
1844 // (*) binder moved here
1845 Where(ty
::Binder(tys
.to_vec()))
1848 ty
::TyAdt(..) | ty
::TyProjection(..) | ty
::TyParam(..) | ty
::TyAnon(..) => {
1849 // Fallback to whatever user-defined impls exist in this case.
1853 ty
::TyInfer(ty
::TyVar(_
)) => {
1854 // Unbound type variable. Might or might not have
1855 // applicable impls and so forth, depending on what
1856 // those type variables wind up being bound to.
1860 ty
::TyInfer(ty
::FreshTy(_
))
1861 | ty
::TyInfer(ty
::FreshIntTy(_
))
1862 | ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1863 bug
!("asked to assemble builtin bounds of unexpected type: {:?}",
1869 /// For default impls, we need to break apart a type into its
1870 /// "constituent types" -- meaning, the types that it contains.
1872 /// Here are some (simple) examples:
1875 /// (i32, u32) -> [i32, u32]
1876 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1877 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1878 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1880 fn constituent_types_for_ty(&self, t
: Ty
<'tcx
>) -> Vec
<Ty
<'tcx
>> {
1890 ty
::TyInfer(ty
::IntVar(_
)) |
1891 ty
::TyInfer(ty
::FloatVar(_
)) |
1899 ty
::TyProjection(..) |
1900 ty
::TyInfer(ty
::TyVar(_
)) |
1901 ty
::TyInfer(ty
::FreshTy(_
)) |
1902 ty
::TyInfer(ty
::FreshIntTy(_
)) |
1903 ty
::TyInfer(ty
::FreshFloatTy(_
)) => {
1904 bug
!("asked to assemble constituent types of unexpected type: {:?}",
1908 ty
::TyRawPtr(ty
::TypeAndMut { ty: element_ty, ..}
) |
1909 ty
::TyRef(_
, ty
::TypeAndMut { ty: element_ty, ..}
) => {
1913 ty
::TyArray(element_ty
, _
) | ty
::TySlice(element_ty
) => {
1917 ty
::TyTuple(ref tys
, _
) => {
1918 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1922 ty
::TyClosure(def_id
, ref substs
) => {
1923 // FIXME(#27086). We are invariant w/r/t our
1924 // func_substs, but we don't see them as
1925 // constituent types; this seems RIGHT but also like
1926 // something that a normal type couldn't simulate. Is
1927 // this just a gap with the way that PhantomData and
1928 // OIBIT interact? That is, there is no way to say
1929 // "make me invariant with respect to this TYPE, but
1930 // do not act as though I can reach it"
1931 substs
.upvar_tys(def_id
, self.tcx()).collect()
1934 // for `PhantomData<T>`, we pass `T`
1935 ty
::TyAdt(def
, substs
) if def
.is_phantom_data() => {
1936 substs
.types().collect()
1939 ty
::TyAdt(def
, substs
) => {
1941 .map(|f
| f
.ty(self.tcx(), substs
))
1945 ty
::TyAnon(def_id
, substs
) => {
1946 // We can resolve the `impl Trait` to its concrete type,
1947 // which enforces a DAG between the functions requiring
1948 // the auto trait bounds in question.
1949 vec
![self.tcx().type_of(def_id
).subst(self.tcx(), substs
)]
1954 fn collect_predicates_for_types(&mut self,
1955 param_env
: ty
::ParamEnv
<'tcx
>,
1956 cause
: ObligationCause
<'tcx
>,
1957 recursion_depth
: usize,
1958 trait_def_id
: DefId
,
1959 types
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
1960 -> Vec
<PredicateObligation
<'tcx
>>
1962 // Because the types were potentially derived from
1963 // higher-ranked obligations they may reference late-bound
1964 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1965 // yield a type like `for<'a> &'a int`. In general, we
1966 // maintain the invariant that we never manipulate bound
1967 // regions, so we have to process these bound regions somehow.
1969 // The strategy is to:
1971 // 1. Instantiate those regions to skolemized regions (e.g.,
1972 // `for<'a> &'a int` becomes `&0 int`.
1973 // 2. Produce something like `&'0 int : Copy`
1974 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1976 types
.skip_binder().into_iter().flat_map(|ty
| { // binder moved -\
1977 let ty
: ty
::Binder
<Ty
<'tcx
>> = ty
::Binder(ty
); // <----------/
1979 self.in_snapshot(|this
, snapshot
| {
1980 let (skol_ty
, skol_map
) =
1981 this
.infcx().skolemize_late_bound_regions(&ty
, snapshot
);
1982 let Normalized { value: normalized_ty, mut obligations }
=
1983 project
::normalize_with_depth(this
,
1988 let skol_obligation
=
1989 this
.tcx().predicate_for_trait_def(param_env
,
1995 obligations
.push(skol_obligation
);
1996 this
.infcx().plug_leaks(skol_map
, snapshot
, obligations
)
2001 ///////////////////////////////////////////////////////////////////////////
2004 // Confirmation unifies the output type parameters of the trait
2005 // with the values found in the obligation, possibly yielding a
2006 // type error. See `README.md` for more details.
2008 fn confirm_candidate(&mut self,
2009 obligation
: &TraitObligation
<'tcx
>,
2010 candidate
: SelectionCandidate
<'tcx
>)
2011 -> Result
<Selection
<'tcx
>,SelectionError
<'tcx
>>
2013 debug
!("confirm_candidate({:?}, {:?})",
2018 BuiltinCandidate { has_nested }
=> {
2020 self.confirm_builtin_candidate(obligation
, has_nested
)))
2023 ParamCandidate(param
) => {
2024 let obligations
= self.confirm_param_candidate(obligation
, param
);
2025 Ok(VtableParam(obligations
))
2028 DefaultImplCandidate(trait_def_id
) => {
2029 let data
= self.confirm_default_impl_candidate(obligation
, trait_def_id
);
2030 Ok(VtableDefaultImpl(data
))
2033 ImplCandidate(impl_def_id
) => {
2034 Ok(VtableImpl(self.confirm_impl_candidate(obligation
, impl_def_id
)))
2037 ClosureCandidate(closure_def_id
, substs
, kind
) => {
2038 let vtable_closure
=
2039 self.confirm_closure_candidate(obligation
, closure_def_id
, substs
, kind
)?
;
2040 Ok(VtableClosure(vtable_closure
))
2043 BuiltinObjectCandidate
=> {
2044 // This indicates something like `(Trait+Send) :
2045 // Send`. In this case, we know that this holds
2046 // because that's what the object type is telling us,
2047 // and there's really no additional obligations to
2048 // prove and no types in particular to unify etc.
2049 Ok(VtableParam(Vec
::new()))
2052 ObjectCandidate
=> {
2053 let data
= self.confirm_object_candidate(obligation
);
2054 Ok(VtableObject(data
))
2057 FnPointerCandidate
=> {
2059 self.confirm_fn_pointer_candidate(obligation
)?
;
2060 Ok(VtableFnPointer(data
))
2063 ProjectionCandidate
=> {
2064 self.confirm_projection_candidate(obligation
);
2065 Ok(VtableParam(Vec
::new()))
2068 BuiltinUnsizeCandidate
=> {
2069 let data
= self.confirm_builtin_unsize_candidate(obligation
)?
;
2070 Ok(VtableBuiltin(data
))
2075 fn confirm_projection_candidate(&mut self,
2076 obligation
: &TraitObligation
<'tcx
>)
2078 self.in_snapshot(|this
, snapshot
| {
2080 this
.match_projection_obligation_against_definition_bounds(obligation
,
2086 fn confirm_param_candidate(&mut self,
2087 obligation
: &TraitObligation
<'tcx
>,
2088 param
: ty
::PolyTraitRef
<'tcx
>)
2089 -> Vec
<PredicateObligation
<'tcx
>>
2091 debug
!("confirm_param_candidate({:?},{:?})",
2095 // During evaluation, we already checked that this
2096 // where-clause trait-ref could be unified with the obligation
2097 // trait-ref. Repeat that unification now without any
2098 // transactional boundary; it should not fail.
2099 match self.match_where_clause_trait_ref(obligation
, param
.clone()) {
2100 Ok(obligations
) => obligations
,
2102 bug
!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2109 fn confirm_builtin_candidate(&mut self,
2110 obligation
: &TraitObligation
<'tcx
>,
2112 -> VtableBuiltinData
<PredicateObligation
<'tcx
>>
2114 debug
!("confirm_builtin_candidate({:?}, {:?})",
2115 obligation
, has_nested
);
2117 let obligations
= if has_nested
{
2118 let trait_def
= obligation
.predicate
.def_id();
2119 let conditions
= match trait_def
{
2120 _
if Some(trait_def
) == self.tcx().lang_items
.sized_trait() => {
2121 self.sized_conditions(obligation
)
2123 _
if Some(trait_def
) == self.tcx().lang_items
.copy_trait() => {
2124 self.copy_conditions(obligation
)
2126 _
=> bug
!("unexpected builtin trait {:?}", trait_def
)
2128 let nested
= match conditions
{
2129 BuiltinImplConditions
::Where(nested
) => nested
,
2130 _
=> bug
!("obligation {:?} had matched a builtin impl but now doesn't",
2134 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2135 self.collect_predicates_for_types(obligation
.param_env
,
2137 obligation
.recursion_depth
+1,
2144 debug
!("confirm_builtin_candidate: obligations={:?}",
2146 VtableBuiltinData { nested: obligations }
2149 /// This handles the case where a `impl Foo for ..` impl is being used.
2150 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2152 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2153 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2154 fn confirm_default_impl_candidate(&mut self,
2155 obligation
: &TraitObligation
<'tcx
>,
2156 trait_def_id
: DefId
)
2157 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2159 debug
!("confirm_default_impl_candidate({:?}, {:?})",
2163 // binder is moved below
2164 let self_ty
= self.infcx
.shallow_resolve(obligation
.predicate
.skip_binder().self_ty());
2165 let types
= self.constituent_types_for_ty(self_ty
);
2166 self.vtable_default_impl(obligation
, trait_def_id
, ty
::Binder(types
))
2169 /// See `confirm_default_impl_candidate`
2170 fn vtable_default_impl(&mut self,
2171 obligation
: &TraitObligation
<'tcx
>,
2172 trait_def_id
: DefId
,
2173 nested
: ty
::Binder
<Vec
<Ty
<'tcx
>>>)
2174 -> VtableDefaultImplData
<PredicateObligation
<'tcx
>>
2176 debug
!("vtable_default_impl: nested={:?}", nested
);
2178 let cause
= obligation
.derived_cause(BuiltinDerivedObligation
);
2179 let mut obligations
= self.collect_predicates_for_types(
2180 obligation
.param_env
,
2182 obligation
.recursion_depth
+1,
2186 let trait_obligations
= self.in_snapshot(|this
, snapshot
| {
2187 let poly_trait_ref
= obligation
.predicate
.to_poly_trait_ref();
2188 let (trait_ref
, skol_map
) =
2189 this
.infcx().skolemize_late_bound_regions(&poly_trait_ref
, snapshot
);
2190 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2191 this
.impl_or_trait_obligations(cause
,
2192 obligation
.recursion_depth
+ 1,
2193 obligation
.param_env
,
2200 obligations
.extend(trait_obligations
);
2202 debug
!("vtable_default_impl: obligations={:?}", obligations
);
2204 VtableDefaultImplData
{
2205 trait_def_id
: trait_def_id
,
2210 fn confirm_impl_candidate(&mut self,
2211 obligation
: &TraitObligation
<'tcx
>,
2213 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2215 debug
!("confirm_impl_candidate({:?},{:?})",
2219 // First, create the substitutions by matching the impl again,
2220 // this time not in a probe.
2221 self.in_snapshot(|this
, snapshot
| {
2222 let (substs
, skol_map
) =
2223 this
.rematch_impl(impl_def_id
, obligation
,
2225 debug
!("confirm_impl_candidate substs={:?}", substs
);
2226 let cause
= obligation
.derived_cause(ImplDerivedObligation
);
2227 this
.vtable_impl(impl_def_id
,
2230 obligation
.recursion_depth
+ 1,
2231 obligation
.param_env
,
2237 fn vtable_impl(&mut self,
2239 mut substs
: Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2240 cause
: ObligationCause
<'tcx
>,
2241 recursion_depth
: usize,
2242 param_env
: ty
::ParamEnv
<'tcx
>,
2243 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2244 snapshot
: &infer
::CombinedSnapshot
)
2245 -> VtableImplData
<'tcx
, PredicateObligation
<'tcx
>>
2247 debug
!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2253 let mut impl_obligations
=
2254 self.impl_or_trait_obligations(cause
,
2262 debug
!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2266 // Because of RFC447, the impl-trait-ref and obligations
2267 // are sufficient to determine the impl substs, without
2268 // relying on projections in the impl-trait-ref.
2270 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2271 impl_obligations
.append(&mut substs
.obligations
);
2273 VtableImplData
{ impl_def_id
: impl_def_id
,
2274 substs
: substs
.value
,
2275 nested
: impl_obligations
}
2278 fn confirm_object_candidate(&mut self,
2279 obligation
: &TraitObligation
<'tcx
>)
2280 -> VtableObjectData
<'tcx
, PredicateObligation
<'tcx
>>
2282 debug
!("confirm_object_candidate({:?})",
2285 // FIXME skipping binder here seems wrong -- we should
2286 // probably flatten the binder from the obligation and the
2287 // binder from the object. Have to try to make a broken test
2288 // case that results. -nmatsakis
2289 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2290 let poly_trait_ref
= match self_ty
.sty
{
2291 ty
::TyDynamic(ref data
, ..) => {
2292 data
.principal().unwrap().with_self_ty(self.tcx(), self_ty
)
2295 span_bug
!(obligation
.cause
.span
,
2296 "object candidate with non-object");
2300 let mut upcast_trait_ref
= None
;
2304 let tcx
= self.tcx();
2306 // We want to find the first supertrait in the list of
2307 // supertraits that we can unify with, and do that
2308 // unification. We know that there is exactly one in the list
2309 // where we can unify because otherwise select would have
2310 // reported an ambiguity. (When we do find a match, also
2311 // record it for later.)
2313 util
::supertraits(tcx
, poly_trait_ref
)
2317 |this
, _
| this
.match_poly_trait_ref(obligation
, t
))
2319 Ok(_
) => { upcast_trait_ref = Some(t); false }
2324 // Additionally, for each of the nonmatching predicates that
2325 // we pass over, we sum up the set of number of vtable
2326 // entries, so that we can compute the offset for the selected
2329 nonmatching
.map(|t
| tcx
.count_own_vtable_entries(t
))
2335 upcast_trait_ref
: upcast_trait_ref
.unwrap(),
2336 vtable_base
: vtable_base
,
2341 fn confirm_fn_pointer_candidate(&mut self, obligation
: &TraitObligation
<'tcx
>)
2342 -> Result
<VtableFnPointerData
<'tcx
, PredicateObligation
<'tcx
>>, SelectionError
<'tcx
>>
2344 debug
!("confirm_fn_pointer_candidate({:?})",
2347 // ok to skip binder; it is reintroduced below
2348 let self_ty
= self.infcx
.shallow_resolve(*obligation
.self_ty().skip_binder());
2349 let sig
= self_ty
.fn_sig();
2351 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2354 util
::TupleArgumentsFlag
::Yes
)
2355 .map_bound(|(trait_ref
, _
)| trait_ref
);
2357 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2358 obligation
.param_env
,
2359 obligation
.predicate
.to_poly_trait_ref(),
2361 Ok(VtableFnPointerData { fn_ty: self_ty, nested: vec![] }
)
2364 fn confirm_closure_candidate(&mut self,
2365 obligation
: &TraitObligation
<'tcx
>,
2366 closure_def_id
: DefId
,
2367 substs
: ty
::ClosureSubsts
<'tcx
>,
2368 kind
: ty
::ClosureKind
)
2369 -> Result
<VtableClosureData
<'tcx
, PredicateObligation
<'tcx
>>,
2370 SelectionError
<'tcx
>>
2372 debug
!("confirm_closure_candidate({:?},{:?},{:?})",
2380 } = self.closure_trait_ref(obligation
, closure_def_id
, substs
);
2382 debug
!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2387 self.confirm_poly_trait_refs(obligation
.cause
.clone(),
2388 obligation
.param_env
,
2389 obligation
.predicate
.to_poly_trait_ref(),
2392 obligations
.push(Obligation
::new(
2393 obligation
.cause
.clone(),
2394 obligation
.param_env
,
2395 ty
::Predicate
::ClosureKind(closure_def_id
, kind
)));
2397 Ok(VtableClosureData
{
2398 closure_def_id
: closure_def_id
,
2399 substs
: substs
.clone(),
2404 /// In the case of closure types and fn pointers,
2405 /// we currently treat the input type parameters on the trait as
2406 /// outputs. This means that when we have a match we have only
2407 /// considered the self type, so we have to go back and make sure
2408 /// to relate the argument types too. This is kind of wrong, but
2409 /// since we control the full set of impls, also not that wrong,
2410 /// and it DOES yield better error messages (since we don't report
2411 /// errors as if there is no applicable impl, but rather report
2412 /// errors are about mismatched argument types.
2414 /// Here is an example. Imagine we have a closure expression
2415 /// and we desugared it so that the type of the expression is
2416 /// `Closure`, and `Closure` expects an int as argument. Then it
2417 /// is "as if" the compiler generated this impl:
2419 /// impl Fn(int) for Closure { ... }
2421 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2422 /// we have matched the self-type `Closure`. At this point we'll
2423 /// compare the `int` to `usize` and generate an error.
2425 /// Note that this checking occurs *after* the impl has selected,
2426 /// because these output type parameters should not affect the
2427 /// selection of the impl. Therefore, if there is a mismatch, we
2428 /// report an error to the user.
2429 fn confirm_poly_trait_refs(&mut self,
2430 obligation_cause
: ObligationCause
<'tcx
>,
2431 obligation_param_env
: ty
::ParamEnv
<'tcx
>,
2432 obligation_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
2433 expected_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2434 -> Result
<(), SelectionError
<'tcx
>>
2436 let obligation_trait_ref
= obligation_trait_ref
.clone();
2438 .at(&obligation_cause
, obligation_param_env
)
2439 .sup(obligation_trait_ref
, expected_trait_ref
)
2440 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2441 .map_err(|e
| OutputTypeParameterMismatch(expected_trait_ref
, obligation_trait_ref
, e
))
2444 fn confirm_builtin_unsize_candidate(&mut self,
2445 obligation
: &TraitObligation
<'tcx
>,)
2446 -> Result
<VtableBuiltinData
<PredicateObligation
<'tcx
>>,
2447 SelectionError
<'tcx
>> {
2448 let tcx
= self.tcx();
2450 // assemble_candidates_for_unsizing should ensure there are no late bound
2451 // regions here. See the comment there for more details.
2452 let source
= self.infcx
.shallow_resolve(
2453 tcx
.no_late_bound_regions(&obligation
.self_ty()).unwrap());
2454 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
2455 let target
= self.infcx
.shallow_resolve(target
);
2457 debug
!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2460 let mut nested
= vec
![];
2461 match (&source
.sty
, &target
.sty
) {
2462 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2463 (&ty
::TyDynamic(ref data_a
, r_a
), &ty
::TyDynamic(ref data_b
, r_b
)) => {
2464 // See assemble_candidates_for_unsizing for more info.
2465 // Binders reintroduced below in call to mk_existential_predicates.
2466 let principal
= data_a
.skip_binder().principal();
2467 let iter
= principal
.into_iter().map(ty
::ExistentialPredicate
::Trait
)
2468 .chain(data_a
.skip_binder().projection_bounds()
2469 .map(|x
| ty
::ExistentialPredicate
::Projection(x
)))
2470 .chain(data_b
.auto_traits().map(ty
::ExistentialPredicate
::AutoTrait
));
2471 let new_trait
= tcx
.mk_dynamic(
2472 ty
::Binder(tcx
.mk_existential_predicates(iter
)), r_b
);
2473 let InferOk { obligations, .. }
=
2474 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2475 .eq(target
, new_trait
)
2476 .map_err(|_
| Unimplemented
)?
;
2477 self.inferred_obligations
.extend(obligations
);
2479 // Register one obligation for 'a: 'b.
2480 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2481 obligation
.cause
.body_id
,
2482 ObjectCastObligation(target
));
2483 let outlives
= ty
::OutlivesPredicate(r_a
, r_b
);
2484 nested
.push(Obligation
::with_depth(cause
,
2485 obligation
.recursion_depth
+ 1,
2486 obligation
.param_env
,
2487 ty
::Binder(outlives
).to_predicate()));
2491 (_
, &ty
::TyDynamic(ref data
, r
)) => {
2492 let mut object_dids
=
2493 data
.auto_traits().chain(data
.principal().map(|p
| p
.def_id()));
2494 if let Some(did
) = object_dids
.find(|did
| {
2495 !tcx
.is_object_safe(*did
)
2497 return Err(TraitNotObjectSafe(did
))
2500 let cause
= ObligationCause
::new(obligation
.cause
.span
,
2501 obligation
.cause
.body_id
,
2502 ObjectCastObligation(target
));
2503 let mut push
= |predicate
| {
2504 nested
.push(Obligation
::with_depth(cause
.clone(),
2505 obligation
.recursion_depth
+ 1,
2506 obligation
.param_env
,
2510 // Create obligations:
2511 // - Casting T to Trait
2512 // - For all the various builtin bounds attached to the object cast. (In other
2513 // words, if the object type is Foo+Send, this would create an obligation for the
2515 // - Projection predicates
2516 for predicate
in data
.iter() {
2517 push(predicate
.with_self_ty(tcx
, source
));
2520 // We can only make objects from sized types.
2521 let tr
= ty
::TraitRef
{
2522 def_id
: tcx
.require_lang_item(lang_items
::SizedTraitLangItem
),
2523 substs
: tcx
.mk_substs_trait(source
, &[]),
2525 push(tr
.to_predicate());
2527 // If the type is `Foo+'a`, ensures that the type
2528 // being cast to `Foo+'a` outlives `'a`:
2529 let outlives
= ty
::OutlivesPredicate(source
, r
);
2530 push(ty
::Binder(outlives
).to_predicate());
2534 (&ty
::TyArray(a
, _
), &ty
::TySlice(b
)) => {
2535 let InferOk { obligations, .. }
=
2536 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2538 .map_err(|_
| Unimplemented
)?
;
2539 self.inferred_obligations
.extend(obligations
);
2542 // Struct<T> -> Struct<U>.
2543 (&ty
::TyAdt(def
, substs_a
), &ty
::TyAdt(_
, substs_b
)) => {
2546 .map(|f
| tcx
.type_of(f
.did
))
2547 .collect
::<Vec
<_
>>();
2549 // The last field of the structure has to exist and contain type parameters.
2550 let field
= if let Some(&field
) = fields
.last() {
2553 return Err(Unimplemented
);
2555 let mut ty_params
= BitVector
::new(substs_a
.types().count());
2556 let mut found
= false;
2557 for ty
in field
.walk() {
2558 if let ty
::TyParam(p
) = ty
.sty
{
2559 ty_params
.insert(p
.idx
as usize);
2564 return Err(Unimplemented
);
2567 // Replace type parameters used in unsizing with
2568 // TyError and ensure they do not affect any other fields.
2569 // This could be checked after type collection for any struct
2570 // with a potentially unsized trailing field.
2571 let params
= substs_a
.iter().enumerate().map(|(i
, &k
)| {
2572 if ty_params
.contains(i
) {
2573 Kind
::from(tcx
.types
.err
)
2578 let substs
= tcx
.mk_substs(params
);
2579 for &ty
in fields
.split_last().unwrap().1 {
2580 if ty
.subst(tcx
, substs
).references_error() {
2581 return Err(Unimplemented
);
2585 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2586 let inner_source
= field
.subst(tcx
, substs_a
);
2587 let inner_target
= field
.subst(tcx
, substs_b
);
2589 // Check that the source structure with the target's
2590 // type parameters is a subtype of the target.
2591 let params
= substs_a
.iter().enumerate().map(|(i
, &k
)| {
2592 if ty_params
.contains(i
) {
2593 Kind
::from(substs_b
.type_at(i
))
2598 let new_struct
= tcx
.mk_adt(def
, tcx
.mk_substs(params
));
2599 let InferOk { obligations, .. }
=
2600 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2601 .eq(target
, new_struct
)
2602 .map_err(|_
| Unimplemented
)?
;
2603 self.inferred_obligations
.extend(obligations
);
2605 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2606 nested
.push(tcx
.predicate_for_trait_def(
2607 obligation
.param_env
,
2608 obligation
.cause
.clone(),
2609 obligation
.predicate
.def_id(),
2610 obligation
.recursion_depth
+ 1,
2618 Ok(VtableBuiltinData { nested: nested }
)
2621 ///////////////////////////////////////////////////////////////////////////
2624 // Matching is a common path used for both evaluation and
2625 // confirmation. It basically unifies types that appear in impls
2626 // and traits. This does affect the surrounding environment;
2627 // therefore, when used during evaluation, match routines must be
2628 // run inside of a `probe()` so that their side-effects are
2631 fn rematch_impl(&mut self,
2633 obligation
: &TraitObligation
<'tcx
>,
2634 snapshot
: &infer
::CombinedSnapshot
)
2635 -> (Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2636 infer
::SkolemizationMap
<'tcx
>)
2638 match self.match_impl(impl_def_id
, obligation
, snapshot
) {
2639 Ok((substs
, skol_map
)) => (substs
, skol_map
),
2641 bug
!("Impl {:?} was matchable against {:?} but now is not",
2648 fn match_impl(&mut self,
2650 obligation
: &TraitObligation
<'tcx
>,
2651 snapshot
: &infer
::CombinedSnapshot
)
2652 -> Result
<(Normalized
<'tcx
, &'tcx Substs
<'tcx
>>,
2653 infer
::SkolemizationMap
<'tcx
>), ()>
2655 let impl_trait_ref
= self.tcx().impl_trait_ref(impl_def_id
).unwrap();
2657 // Before we create the substitutions and everything, first
2658 // consider a "quick reject". This avoids creating more types
2659 // and so forth that we need to.
2660 if self.fast_reject_trait_refs(obligation
, &impl_trait_ref
) {
2664 let (skol_obligation
, skol_map
) = self.infcx().skolemize_late_bound_regions(
2665 &obligation
.predicate
,
2667 let skol_obligation_trait_ref
= skol_obligation
.trait_ref
;
2669 let impl_substs
= self.infcx
.fresh_substs_for_item(obligation
.cause
.span
,
2672 let impl_trait_ref
= impl_trait_ref
.subst(self.tcx(),
2675 let impl_trait_ref
=
2676 project
::normalize_with_depth(self,
2677 obligation
.param_env
,
2678 obligation
.cause
.clone(),
2679 obligation
.recursion_depth
+ 1,
2682 debug
!("match_impl(impl_def_id={:?}, obligation={:?}, \
2683 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2687 skol_obligation_trait_ref
);
2689 let InferOk { obligations, .. }
=
2690 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2691 .eq(skol_obligation_trait_ref
, impl_trait_ref
.value
)
2693 debug
!("match_impl: failed eq_trait_refs due to `{}`", e
);
2696 self.inferred_obligations
.extend(obligations
);
2698 if let Err(e
) = self.infcx
.leak_check(false,
2699 obligation
.cause
.span
,
2702 debug
!("match_impl: failed leak check due to `{}`", e
);
2706 debug
!("match_impl: success impl_substs={:?}", impl_substs
);
2709 obligations
: impl_trait_ref
.obligations
2713 fn fast_reject_trait_refs(&mut self,
2714 obligation
: &TraitObligation
,
2715 impl_trait_ref
: &ty
::TraitRef
)
2718 // We can avoid creating type variables and doing the full
2719 // substitution if we find that any of the input types, when
2720 // simplified, do not match.
2722 obligation
.predicate
.skip_binder().input_types()
2723 .zip(impl_trait_ref
.input_types())
2724 .any(|(obligation_ty
, impl_ty
)| {
2725 let simplified_obligation_ty
=
2726 fast_reject
::simplify_type(self.tcx(), obligation_ty
, true);
2727 let simplified_impl_ty
=
2728 fast_reject
::simplify_type(self.tcx(), impl_ty
, false);
2730 simplified_obligation_ty
.is_some() &&
2731 simplified_impl_ty
.is_some() &&
2732 simplified_obligation_ty
!= simplified_impl_ty
2736 /// Normalize `where_clause_trait_ref` and try to match it against
2737 /// `obligation`. If successful, return any predicates that
2738 /// result from the normalization. Normalization is necessary
2739 /// because where-clauses are stored in the parameter environment
2741 fn match_where_clause_trait_ref(&mut self,
2742 obligation
: &TraitObligation
<'tcx
>,
2743 where_clause_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2744 -> Result
<Vec
<PredicateObligation
<'tcx
>>,()>
2746 self.match_poly_trait_ref(obligation
, where_clause_trait_ref
)?
;
2750 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2751 /// obligation is satisfied.
2752 fn match_poly_trait_ref(&mut self,
2753 obligation
: &TraitObligation
<'tcx
>,
2754 poly_trait_ref
: ty
::PolyTraitRef
<'tcx
>)
2757 debug
!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2761 self.infcx
.at(&obligation
.cause
, obligation
.param_env
)
2762 .sup(obligation
.predicate
.to_poly_trait_ref(), poly_trait_ref
)
2763 .map(|InferOk { obligations, .. }
| self.inferred_obligations
.extend(obligations
))
2767 ///////////////////////////////////////////////////////////////////////////
2770 fn match_fresh_trait_refs(&self,
2771 previous
: &ty
::PolyTraitRef
<'tcx
>,
2772 current
: &ty
::PolyTraitRef
<'tcx
>)
2775 let mut matcher
= ty
::_match
::Match
::new(self.tcx());
2776 matcher
.relate(previous
, current
).is_ok()
2779 fn push_stack
<'o
,'s
:'o
>(&mut self,
2780 previous_stack
: TraitObligationStackList
<'s
, 'tcx
>,
2781 obligation
: &'o TraitObligation
<'tcx
>)
2782 -> TraitObligationStack
<'o
, 'tcx
>
2784 let fresh_trait_ref
=
2785 obligation
.predicate
.to_poly_trait_ref().fold_with(&mut self.freshener
);
2787 TraitObligationStack
{
2788 obligation
: obligation
,
2789 fresh_trait_ref
: fresh_trait_ref
,
2790 previous
: previous_stack
,
2794 fn closure_trait_ref_unnormalized(&mut self,
2795 obligation
: &TraitObligation
<'tcx
>,
2796 closure_def_id
: DefId
,
2797 substs
: ty
::ClosureSubsts
<'tcx
>)
2798 -> ty
::PolyTraitRef
<'tcx
>
2800 let closure_type
= self.infcx
.closure_type(closure_def_id
)
2801 .subst(self.tcx(), substs
.substs
);
2802 let ty
::Binder((trait_ref
, _
)) =
2803 self.tcx().closure_trait_ref_and_return_type(obligation
.predicate
.def_id(),
2804 obligation
.predicate
.0.self_ty(), // (1)
2806 util
::TupleArgumentsFlag
::No
);
2807 // (1) Feels icky to skip the binder here, but OTOH we know
2808 // that the self-type is an unboxed closure type and hence is
2809 // in fact unparameterized (or at least does not reference any
2810 // regions bound in the obligation). Still probably some
2811 // refactoring could make this nicer.
2813 ty
::Binder(trait_ref
)
2816 fn closure_trait_ref(&mut self,
2817 obligation
: &TraitObligation
<'tcx
>,
2818 closure_def_id
: DefId
,
2819 substs
: ty
::ClosureSubsts
<'tcx
>)
2820 -> Normalized
<'tcx
, ty
::PolyTraitRef
<'tcx
>>
2822 let trait_ref
= self.closure_trait_ref_unnormalized(
2823 obligation
, closure_def_id
, substs
);
2825 // A closure signature can contain associated types which
2826 // must be normalized.
2827 normalize_with_depth(self,
2828 obligation
.param_env
,
2829 obligation
.cause
.clone(),
2830 obligation
.recursion_depth
+1,
2834 /// Returns the obligations that are implied by instantiating an
2835 /// impl or trait. The obligations are substituted and fully
2836 /// normalized. This is used when confirming an impl or default
2838 fn impl_or_trait_obligations(&mut self,
2839 cause
: ObligationCause
<'tcx
>,
2840 recursion_depth
: usize,
2841 param_env
: ty
::ParamEnv
<'tcx
>,
2842 def_id
: DefId
, // of impl or trait
2843 substs
: &Substs
<'tcx
>, // for impl or trait
2844 skol_map
: infer
::SkolemizationMap
<'tcx
>,
2845 snapshot
: &infer
::CombinedSnapshot
)
2846 -> Vec
<PredicateObligation
<'tcx
>>
2848 debug
!("impl_or_trait_obligations(def_id={:?})", def_id
);
2849 let tcx
= self.tcx();
2851 // To allow for one-pass evaluation of the nested obligation,
2852 // each predicate must be preceded by the obligations required
2854 // for example, if we have:
2855 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2856 // the impl will have the following predicates:
2857 // <V as Iterator>::Item = U,
2858 // U: Iterator, U: Sized,
2859 // V: Iterator, V: Sized,
2860 // <U as Iterator>::Item: Copy
2861 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2862 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2863 // `$1: Copy`, so we must ensure the obligations are emitted in
2865 let predicates
= tcx
.predicates_of(def_id
);
2866 assert_eq
!(predicates
.parent
, None
);
2867 let predicates
= predicates
.predicates
.iter().flat_map(|predicate
| {
2868 let predicate
= normalize_with_depth(self, param_env
, cause
.clone(), recursion_depth
,
2869 &predicate
.subst(tcx
, substs
));
2870 predicate
.obligations
.into_iter().chain(
2872 cause
: cause
.clone(),
2873 recursion_depth
: recursion_depth
,
2875 predicate
: predicate
.value
2878 self.infcx().plug_leaks(skol_map
, snapshot
, predicates
)
2882 impl<'tcx
> TraitObligation
<'tcx
> {
2883 #[allow(unused_comparisons)]
2884 pub fn derived_cause(&self,
2885 variant
: fn(DerivedObligationCause
<'tcx
>) -> ObligationCauseCode
<'tcx
>)
2886 -> ObligationCause
<'tcx
>
2889 * Creates a cause for obligations that are derived from
2890 * `obligation` by a recursive search (e.g., for a builtin
2891 * bound, or eventually a `impl Foo for ..`). If `obligation`
2892 * is itself a derived obligation, this is just a clone, but
2893 * otherwise we create a "derived obligation" cause so as to
2894 * keep track of the original root obligation for error
2898 let obligation
= self;
2900 // NOTE(flaper87): As of now, it keeps track of the whole error
2901 // chain. Ideally, we should have a way to configure this either
2902 // by using -Z verbose or just a CLI argument.
2903 if obligation
.recursion_depth
>= 0 {
2904 let derived_cause
= DerivedObligationCause
{
2905 parent_trait_ref
: obligation
.predicate
.to_poly_trait_ref(),
2906 parent_code
: Rc
::new(obligation
.cause
.code
.clone())
2908 let derived_code
= variant(derived_cause
);
2909 ObligationCause
::new(obligation
.cause
.span
, obligation
.cause
.body_id
, derived_code
)
2911 obligation
.cause
.clone()
2916 impl<'tcx
> SelectionCache
<'tcx
> {
2917 pub fn new() -> SelectionCache
<'tcx
> {
2919 hashmap
: RefCell
::new(FxHashMap())
2924 impl<'tcx
> EvaluationCache
<'tcx
> {
2925 pub fn new() -> EvaluationCache
<'tcx
> {
2927 hashmap
: RefCell
::new(FxHashMap())
2932 impl<'o
,'tcx
> TraitObligationStack
<'o
,'tcx
> {
2933 fn list(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2934 TraitObligationStackList
::with(self)
2937 fn iter(&'o
self) -> TraitObligationStackList
<'o
,'tcx
> {
2942 #[derive(Copy, Clone)]
2943 struct TraitObligationStackList
<'o
,'tcx
:'o
> {
2944 head
: Option
<&'o TraitObligationStack
<'o
,'tcx
>>
2947 impl<'o
,'tcx
> TraitObligationStackList
<'o
,'tcx
> {
2948 fn empty() -> TraitObligationStackList
<'o
,'tcx
> {
2949 TraitObligationStackList { head: None }
2952 fn with(r
: &'o TraitObligationStack
<'o
,'tcx
>) -> TraitObligationStackList
<'o
,'tcx
> {
2953 TraitObligationStackList { head: Some(r) }
2957 impl<'o
,'tcx
> Iterator
for TraitObligationStackList
<'o
,'tcx
>{
2958 type Item
= &'o TraitObligationStack
<'o
,'tcx
>;
2960 fn next(&mut self) -> Option
<&'o TraitObligationStack
<'o
,'tcx
>> {
2971 impl<'o
,'tcx
> fmt
::Debug
for TraitObligationStack
<'o
,'tcx
> {
2972 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
2973 write
!(f
, "TraitObligationStack({:?})", self.obligation
)
2977 impl EvaluationResult
{
2978 fn may_apply(&self) -> bool
{
2982 EvaluatedToUnknown
=> true,
2984 EvaluatedToErr
=> false