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 `doc.rs` for high-level documentation
12 #![allow(dead_code)] // FIXME -- just temporarily
14 pub use self::MethodMatchResult::*;
15 pub use self::MethodMatchedData::*;
16 use self::SelectionCandidate::*;
17 use self::BuiltinBoundConditions::*;
18 use self::EvaluationResult::*;
20 use super::{DerivedObligationCause};
22 use super::project::Normalized;
23 use super::{PredicateObligation, TraitObligation, ObligationCause};
24 use super::{ObligationCauseCode, BuiltinDerivedObligation};
25 use super::{SelectionError, Unimplemented, Overflow, OutputTypeParameterMismatch};
26 use super::{Selection};
27 use super::{SelectionResult};
28 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
29 VtableFnPointer, VtableObject};
30 use super::{VtableImplData, VtableObjectData, VtableBuiltinData};
31 use super::object_safety;
34 use middle::fast_reject;
35 use middle::subst::{Subst, Substs, TypeSpace, VecPerParamSpace};
36 use middle::ty::{self, RegionEscape, ToPolyTraitRef, Ty};
38 use middle::infer::{InferCtxt, TypeFreshener};
39 use middle::ty_fold::TypeFoldable;
40 use std::cell::RefCell;
41 use std::collections::hash_map::HashMap;
43 use syntax::{abi, ast};
44 use util::common::ErrorReported;
45 use util::ppaux::Repr;
47 pub struct SelectionContext<'cx, 'tcx:'cx> {
48 infcx: &'cx InferCtxt<'cx, 'tcx>,
49 closure_typer: &'cx (ty::ClosureTyper<'tcx>+'cx),
51 /// Freshener used specifically for skolemizing entries on the
52 /// obligation stack. This ensures that all entries on the stack
53 /// at one time will have the same set of skolemized entries,
54 /// which is important for checking for trait bounds that
55 /// recursively require themselves.
56 freshener: TypeFreshener<'cx, 'tcx>,
58 /// If true, indicates that the evaluation should be conservative
59 /// and consider the possibility of types outside this crate.
60 /// This comes up primarily when resolving ambiguity. Imagine
61 /// there is some trait reference `$0 : Bar` where `$0` is an
62 /// inference variable. If `intercrate` is true, then we can never
63 /// say for sure that this reference is not implemented, even if
64 /// there are *no impls at all for `Bar`*, because `$0` could be
65 /// bound to some type that in a downstream crate that implements
66 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
67 /// though, we set this to false, because we are only interested
68 /// in types that the user could actually have written --- in
69 /// other words, we consider `$0 : Bar` to be unimplemented if
70 /// there is no type that the user could *actually name* that
71 /// would satisfy it. This avoids crippling inference, basically.
75 // A stack that walks back up the stack frame.
76 struct TraitObligationStack<'prev, 'tcx: 'prev> {
77 obligation: &'prev TraitObligation<'tcx>,
79 /// Trait ref from `obligation` but skolemized with the
80 /// selection-context's freshener. Used to check for recursion.
81 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
83 previous: Option<&'prev TraitObligationStack<'prev, 'tcx>>
87 pub struct SelectionCache<'tcx> {
88 hashmap: RefCell<HashMap<Rc<ty::TraitRef<'tcx>>,
89 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
92 pub enum MethodMatchResult {
93 MethodMatched(MethodMatchedData),
94 MethodAmbiguous(/* list of impls that could apply */ Vec<ast::DefId>),
98 #[derive(Copy, Debug)]
99 pub enum MethodMatchedData {
100 // In the case of a precise match, we don't really need to store
101 // how the match was found. So don't.
104 // In the case of a coercion, we need to know the precise impl so
105 // that we can determine the type to which things were coerced.
106 CoerciveMethodMatch(/* impl we matched */ ast::DefId)
109 /// The selection process begins by considering all impls, where
110 /// clauses, and so forth that might resolve an obligation. Sometimes
111 /// we'll be able to say definitively that (e.g.) an impl does not
112 /// apply to the obligation: perhaps it is defined for `uint` but the
113 /// obligation is for `int`. In that case, we drop the impl out of the
114 /// list. But the other cases are considered *candidates*.
116 /// Candidates can either be definitive or ambiguous. An ambiguous
117 /// candidate is one that might match or might not, depending on how
118 /// type variables wind up being resolved. This only occurs during inference.
120 /// For selection to succeed, there must be exactly one non-ambiguous
121 /// candidate. Usually, it is not possible to have more than one
122 /// definitive candidate, due to the coherence rules. However, there is
123 /// one case where it could occur: if there is a blanket impl for a
124 /// trait (that is, an impl applied to all T), and a type parameter
125 /// with a where clause. In that case, we can have a candidate from the
126 /// where clause and a second candidate from the impl. This is not a
127 /// problem because coherence guarantees us that the impl which would
128 /// be used to satisfy the where clause is the same one that we see
129 /// now. To resolve this issue, therefore, we ignore impls if we find a
130 /// matching where clause. Part of the reason for this is that where
131 /// clauses can give additional information (like, the types of output
132 /// parameters) that would have to be inferred from the impl.
133 #[derive(PartialEq,Eq,Debug,Clone)]
134 enum SelectionCandidate<'tcx> {
135 BuiltinCandidate(ty::BuiltinBound),
136 ParamCandidate(ty::PolyTraitRef<'tcx>),
137 ImplCandidate(ast::DefId),
139 /// This is a trait matching with a projected type as `Self`, and
140 /// we found an applicable bound in the trait definition.
143 /// Implementation of a `Fn`-family trait by one of the
144 /// anonymous types generated for a `||` expression.
145 ClosureCandidate(/* closure */ ast::DefId, Substs<'tcx>),
147 /// Implementation of a `Fn`-family trait by one of the anonymous
148 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
156 struct SelectionCandidateSet<'tcx> {
157 // a list of candidates that definitely apply to the current
158 // obligation (meaning: types unify).
159 vec: Vec<SelectionCandidate<'tcx>>,
161 // if this is true, then there were candidates that might or might
162 // not have applied, but we couldn't tell. This occurs when some
163 // of the input types are type variables, in which case there are
164 // various "builtin" rules that might or might not trigger.
168 enum BuiltinBoundConditions<'tcx> {
175 enum EvaluationResult<'tcx> {
178 EvaluatedToErr(SelectionError<'tcx>),
181 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
182 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>,
183 closure_typer: &'cx ty::ClosureTyper<'tcx>)
184 -> SelectionContext<'cx, 'tcx> {
187 closure_typer: closure_typer,
188 freshener: infcx.freshener(),
193 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>,
194 closure_typer: &'cx ty::ClosureTyper<'tcx>)
195 -> SelectionContext<'cx, 'tcx> {
198 closure_typer: closure_typer,
199 freshener: infcx.freshener(),
204 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
208 pub fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
212 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
213 self.closure_typer.param_env()
216 pub fn closure_typer(&self) -> &'cx (ty::ClosureTyper<'tcx>+'cx) {
220 ///////////////////////////////////////////////////////////////////////////
223 // The selection phase tries to identify *how* an obligation will
224 // be resolved. For example, it will identify which impl or
225 // parameter bound is to be used. The process can be inconclusive
226 // if the self type in the obligation is not fully inferred. Selection
227 // can result in an error in one of two ways:
229 // 1. If no applicable impl or parameter bound can be found.
230 // 2. If the output type parameters in the obligation do not match
231 // those specified by the impl/bound. For example, if the obligation
232 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
233 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
235 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
236 /// type environment by performing unification.
237 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
238 -> SelectionResult<'tcx, Selection<'tcx>> {
239 debug!("select({})", obligation.repr(self.tcx()));
240 assert!(!obligation.predicate.has_escaping_regions());
242 let stack = self.push_stack(None, obligation);
243 match try!(self.candidate_from_obligation(&stack)) {
245 self.consider_unification_despite_ambiguity(obligation);
248 Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))),
252 /// In the particular case of unboxed closure obligations, we can
253 /// sometimes do some amount of unification for the
254 /// argument/return types even though we can't yet fully match obligation.
255 /// The particular case we are interesting in is an obligation of the form:
259 /// where `C` is an unboxed closure type and `FnFoo` is one of the
260 /// `Fn` traits. Because we know that users cannot write impls for closure types
261 /// themselves, the only way that `C : FnFoo` can fail to match is under two
264 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
265 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
266 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
268 /// In either case, we always know what argument types are
269 /// expected by `C`, no matter what kind of `Fn` trait it
270 /// eventually matches. So we can go ahead and unify the argument
271 /// types, even though the end result is ambiguous.
273 /// Note that this is safe *even if* the trait would never be
274 /// matched (case 2 above). After all, in that case, an error will
275 /// result, so it kind of doesn't matter what we do --- unifying
276 /// the argument types can only be helpful to the user, because
277 /// once they patch up the kind of closure that is expected, the
278 /// argment types won't really change.
279 fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligation<'tcx>) {
280 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
281 match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
286 // Is the self-type a closure type? We ignore bindings here
287 // because if it is a closure type, it must be a closure type from
288 // within this current fn, and hence none of the higher-ranked
289 // lifetimes can appear inside the self-type.
290 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
291 let (closure_def_id, substs) = match self_ty.sty {
292 ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
295 assert!(!substs.has_escaping_regions());
297 let closure_trait_ref = self.closure_trait_ref(obligation, closure_def_id, substs);
298 match self.confirm_poly_trait_refs(obligation.cause.clone(),
299 obligation.predicate.to_poly_trait_ref(),
302 Err(_) => { /* Silently ignore errors. */ }
306 ///////////////////////////////////////////////////////////////////////////
309 // Tests whether an obligation can be selected or whether an impl
310 // can be applied to particular types. It skips the "confirmation"
311 // step and hence completely ignores output type parameters.
313 // The result is "true" if the obligation *may* hold and "false" if
314 // we can be sure it does not.
316 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
317 pub fn evaluate_obligation(&mut self,
318 obligation: &PredicateObligation<'tcx>)
321 debug!("evaluate_obligation({})",
322 obligation.repr(self.tcx()));
324 self.evaluate_predicate_recursively(None, obligation).may_apply()
327 fn evaluate_builtin_bound_recursively<'o>(&mut self,
328 bound: ty::BuiltinBound,
329 previous_stack: &TraitObligationStack<'o, 'tcx>,
331 -> EvaluationResult<'tcx>
334 util::predicate_for_builtin_bound(
336 previous_stack.obligation.cause.clone(),
338 previous_stack.obligation.recursion_depth + 1,
343 self.evaluate_predicate_recursively(Some(previous_stack), &obligation)
345 Err(ErrorReported) => {
351 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
352 stack: Option<&TraitObligationStack<'o, 'tcx>>,
354 -> EvaluationResult<'tcx>
355 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
357 let mut result = EvaluatedToOk;
358 for obligation in predicates {
359 match self.evaluate_predicate_recursively(stack, obligation) {
360 EvaluatedToErr(e) => { return EvaluatedToErr(e); }
361 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
368 fn evaluate_predicate_recursively<'o>(&mut self,
369 previous_stack: Option<&TraitObligationStack<'o, 'tcx>>,
370 obligation: &PredicateObligation<'tcx>)
371 -> EvaluationResult<'tcx>
373 debug!("evaluate_predicate_recursively({})",
374 obligation.repr(self.tcx()));
376 match obligation.predicate {
377 ty::Predicate::Trait(ref t) => {
378 assert!(!t.has_escaping_regions());
379 let obligation = obligation.with(t.clone());
380 self.evaluate_obligation_recursively(previous_stack, &obligation)
383 ty::Predicate::Equate(ref p) => {
384 let result = self.infcx.probe(|_| {
385 self.infcx.equality_predicate(obligation.cause.span, p)
388 Ok(()) => EvaluatedToOk,
389 Err(_) => EvaluatedToErr(Unimplemented),
393 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
394 // we do not consider region relationships when
395 // evaluating trait matches
399 ty::Predicate::Projection(ref data) => {
400 self.infcx.probe(|_| {
401 let project_obligation = obligation.with(data.clone());
402 match project::poly_project_and_unify_type(self, &project_obligation) {
403 Ok(Some(subobligations)) => {
404 self.evaluate_predicates_recursively(previous_stack,
405 subobligations.iter())
411 EvaluatedToErr(Unimplemented)
419 fn evaluate_obligation_recursively<'o>(&mut self,
420 previous_stack: Option<&TraitObligationStack<'o, 'tcx>>,
421 obligation: &TraitObligation<'tcx>)
422 -> EvaluationResult<'tcx>
424 debug!("evaluate_obligation_recursively({})",
425 obligation.repr(self.tcx()));
427 let stack = self.push_stack(previous_stack.map(|x| x), obligation);
429 let result = self.evaluate_stack(&stack);
431 debug!("result: {:?}", result);
435 fn evaluate_stack<'o>(&mut self,
436 stack: &TraitObligationStack<'o, 'tcx>)
437 -> EvaluationResult<'tcx>
439 // In intercrate mode, whenever any of the types are unbound,
440 // there can always be an impl. Even if there are no impls in
441 // this crate, perhaps the type would be unified with
442 // something from another crate that does provide an impl.
444 // In intracrate mode, we must still be conservative. The reason is
445 // that we want to avoid cycles. Imagine an impl like:
447 // impl<T:Eq> Eq for Vec<T>
449 // and a trait reference like `$0 : Eq` where `$0` is an
450 // unbound variable. When we evaluate this trait-reference, we
451 // will unify `$0` with `Vec<$1>` (for some fresh variable
452 // `$1`), on the condition that `$1 : Eq`. We will then wind
453 // up with many candidates (since that are other `Eq` impls
454 // that apply) and try to winnow things down. This results in
455 // a recursive evaluation that `$1 : Eq` -- as you can
456 // imagine, this is just where we started. To avoid that, we
457 // check for unbound variables and return an ambiguous (hence possible)
458 // match if we've seen this trait before.
460 // This suffices to allow chains like `FnMut` implemented in
461 // terms of `Fn` etc, but we could probably make this more
463 let input_types = stack.fresh_trait_ref.0.input_types();
464 let unbound_input_types = input_types.iter().any(|&t| ty::type_is_fresh(t));
466 unbound_input_types &&
468 stack.iter().skip(1).any(
469 |prev| stack.fresh_trait_ref.def_id() == prev.fresh_trait_ref.def_id()))
471 debug!("evaluate_stack({}) --> unbound argument, recursion --> ambiguous",
472 stack.fresh_trait_ref.repr(self.tcx()));
473 return EvaluatedToAmbig;
476 // If there is any previous entry on the stack that precisely
477 // matches this obligation, then we can assume that the
478 // obligation is satisfied for now (still all other conditions
479 // must be met of course). One obvious case this comes up is
480 // marker traits like `Send`. Think of a linked list:
482 // struct List<T> { data: T, next: Option<Box<List<T>>> {
484 // `Box<List<T>>` will be `Send` if `T` is `Send` and
485 // `Option<Box<List<T>>>` is `Send`, and in turn
486 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
489 // Note that we do this comparison using the `fresh_trait_ref`
490 // fields. Because these have all been skolemized using
491 // `self.freshener`, we can be sure that (a) this will not
492 // affect the inferencer state and (b) that if we see two
493 // skolemized types with the same index, they refer to the
494 // same unbound type variable.
497 .skip(1) // skip top-most frame
498 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
500 debug!("evaluate_stack({}) --> recursive",
501 stack.fresh_trait_ref.repr(self.tcx()));
502 return EvaluatedToOk;
505 match self.candidate_from_obligation(stack) {
506 Ok(Some(c)) => self.winnow_candidate(stack, &c),
507 Ok(None) => EvaluatedToAmbig,
508 Err(e) => EvaluatedToErr(e),
512 /// Evaluates whether the impl with id `impl_def_id` could be applied to the self type
513 /// `obligation_self_ty`. This can be used either for trait or inherent impls.
514 pub fn evaluate_impl(&mut self,
515 impl_def_id: ast::DefId,
516 obligation: &TraitObligation<'tcx>)
519 debug!("evaluate_impl(impl_def_id={}, obligation={})",
520 impl_def_id.repr(self.tcx()),
521 obligation.repr(self.tcx()));
523 self.infcx.probe(|snapshot| {
524 let (skol_obligation_trait_ref, skol_map) =
525 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
526 match self.match_impl(impl_def_id, obligation, snapshot,
527 &skol_map, skol_obligation_trait_ref.trait_ref.clone()) {
529 let vtable_impl = self.vtable_impl(impl_def_id,
531 obligation.cause.clone(),
532 obligation.recursion_depth + 1,
535 self.winnow_selection(None, VtableImpl(vtable_impl)).may_apply()
544 ///////////////////////////////////////////////////////////////////////////
545 // CANDIDATE ASSEMBLY
547 // The selection process begins by examining all in-scope impls,
548 // caller obligations, and so forth and assembling a list of
549 // candidates. See `doc.rs` and the `Candidate` type for more details.
551 fn candidate_from_obligation<'o>(&mut self,
552 stack: &TraitObligationStack<'o, 'tcx>)
553 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
555 // Watch out for overflow. This intentionally bypasses (and does
556 // not update) the cache.
557 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
558 if stack.obligation.recursion_depth >= recursion_limit {
559 debug!("{} --> overflow (limit={})",
560 stack.obligation.repr(self.tcx()),
565 // Check the cache. Note that we skolemize the trait-ref
566 // separately rather than using `stack.fresh_trait_ref` -- this
567 // is because we want the unbound variables to be replaced
568 // with fresh skolemized types starting from index 0.
569 let cache_fresh_trait_pred =
570 self.infcx.freshen(stack.obligation.predicate.clone());
571 debug!("candidate_from_obligation(cache_fresh_trait_pred={}, obligation={})",
572 cache_fresh_trait_pred.repr(self.tcx()),
573 stack.repr(self.tcx()));
574 assert!(!stack.obligation.predicate.has_escaping_regions());
576 match self.check_candidate_cache(&cache_fresh_trait_pred) {
578 debug!("CACHE HIT: cache_fresh_trait_pred={}, candidate={}",
579 cache_fresh_trait_pred.repr(self.tcx()),
586 // If no match, compute result and insert into cache.
587 let candidate = self.candidate_from_obligation_no_cache(stack);
589 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
590 debug!("CACHE MISS: cache_fresh_trait_pred={}, candidate={}",
591 cache_fresh_trait_pred.repr(self.tcx()), candidate.repr(self.tcx()));
592 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
598 fn candidate_from_obligation_no_cache<'o>(&mut self,
599 stack: &TraitObligationStack<'o, 'tcx>)
600 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
602 if ty::type_is_error(stack.obligation.predicate.0.self_ty()) {
603 return Ok(Some(ErrorCandidate));
606 let candidate_set = try!(self.assemble_candidates(stack));
608 if candidate_set.ambiguous {
609 debug!("candidate set contains ambig");
613 let mut candidates = candidate_set.vec;
615 debug!("assembled {} candidates for {}: {}",
617 stack.repr(self.tcx()),
618 candidates.repr(self.tcx()));
620 // At this point, we know that each of the entries in the
621 // candidate set is *individually* applicable. Now we have to
622 // figure out if they contain mutual incompatibilities. This
623 // frequently arises if we have an unconstrained input type --
624 // for example, we are looking for $0:Eq where $0 is some
625 // unconstrained type variable. In that case, we'll get a
626 // candidate which assumes $0 == int, one that assumes $0 ==
627 // uint, etc. This spells an ambiguity.
629 // If there is more than one candidate, first winnow them down
630 // by considering extra conditions (nested obligations and so
631 // forth). We don't winnow if there is exactly one
632 // candidate. This is a relatively minor distinction but it
633 // can lead to better inference and error-reporting. An
634 // example would be if there was an impl:
636 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
638 // and we were to see some code `foo.push_clone()` where `boo`
639 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
640 // we were to winnow, we'd wind up with zero candidates.
641 // Instead, we select the right impl now but report `Bar does
642 // not implement Clone`.
643 if candidates.len() > 1 {
644 candidates.retain(|c| self.winnow_candidate(stack, c).may_apply())
647 // If there are STILL multiple candidate, we can further reduce
648 // the list by dropping duplicates.
649 if candidates.len() > 1 {
651 while i < candidates.len() {
653 (0..candidates.len())
655 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
658 debug!("Dropping candidate #{}/{}: {}",
659 i, candidates.len(), candidates[i].repr(self.tcx()));
660 candidates.swap_remove(i);
662 debug!("Retaining candidate #{}/{}: {}",
663 i, candidates.len(), candidates[i].repr(self.tcx()));
669 // If there are *STILL* multiple candidates, give up and
671 if candidates.len() > 1 {
672 debug!("multiple matches, ambig");
677 // If there are *NO* candidates, that there are no impls --
678 // that we know of, anyway. Note that in the case where there
679 // are unbound type variables within the obligation, it might
680 // be the case that you could still satisfy the obligation
681 // from another crate by instantiating the type variables with
682 // a type from another crate that does have an impl. This case
683 // is checked for in `evaluate_stack` (and hence users
684 // who might care about this case, like coherence, should use
686 if candidates.len() == 0 {
687 return Err(Unimplemented);
690 // Just one candidate left.
691 let candidate = candidates.pop().unwrap();
694 ImplCandidate(def_id) => {
695 match ty::trait_impl_polarity(self.tcx(), def_id) {
696 Some(ast::ImplPolarity::Negative) => return Err(Unimplemented),
706 fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
707 // If there are any where-clauses in scope, then we always use
708 // a cache local to this particular scope. Otherwise, we
709 // switch to a global cache. We used to try and draw
710 // finer-grained distinctions, but that led to a serious of
711 // annoying and weird bugs like #22019 and #18290. This simple
712 // rule seems to be pretty clearly safe and also still retains
713 // a very high hit rate (~95% when compiling rustc).
714 if !self.param_env().caller_bounds.is_empty() {
715 return &self.param_env().selection_cache;
718 // Avoid using the master cache during coherence and just rely
719 // on the local cache. This effectively disables caching
720 // during coherence. It is really just a simplification to
721 // avoid us having to fear that coherence results "pollute"
722 // the master cache. Since coherence executes pretty quickly,
723 // it's not worth going to more trouble to increase the
724 // hit-rate I don't think.
726 return &self.param_env().selection_cache;
729 // Otherwise, we can use the global cache.
730 &self.tcx().selection_cache
733 fn check_candidate_cache(&mut self,
734 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
735 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
737 let cache = self.pick_candidate_cache();
738 let hashmap = cache.hashmap.borrow();
739 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).map(|c| (*c).clone())
742 fn insert_candidate_cache(&mut self,
743 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
744 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
746 let cache = self.pick_candidate_cache();
747 let mut hashmap = cache.hashmap.borrow_mut();
748 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
751 fn should_update_candidate_cache(&mut self,
752 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
753 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
756 // In general, it's a good idea to cache results, even
757 // ambiguous ones, to save us some trouble later. But we have
758 // to be careful not to cache results that could be
759 // invalidated later by advances in inference. Normally, this
760 // is not an issue, because any inference variables whose
761 // types are not yet bound are "freshened" in the cache key,
762 // which means that if we later get the same request once that
763 // type variable IS bound, we'll have a different cache key.
764 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
765 // not yet known, we may cache the result as `None`. But if
766 // later `_#0t` is bound to `Bar`, then when we freshen we'll
767 // have `Vec<Bar> : Foo` as the cache key.
769 // HOWEVER, it CAN happen that we get an ambiguity result in
770 // one particular case around closures where the cache key
771 // would not change. That is when the precise types of the
772 // upvars that a closure references have not yet been figured
773 // out (i.e., because it is not yet known if they are captured
774 // by ref, and if by ref, what kind of ref). In these cases,
775 // when matching a builtin bound, we will yield back an
776 // ambiguous result. But the *cache key* is just the closure type,
777 // it doesn't capture the state of the upvar computation.
779 // To avoid this trap, just don't cache ambiguous results if
780 // the self-type contains no inference byproducts (that really
781 // shouldn't happen in other circumstances anyway, given
785 Ok(Some(_)) | Err(_) => true,
787 cache_fresh_trait_pred.0.input_types().iter().any(|&t| ty::type_has_ty_infer(t))
792 fn assemble_candidates<'o>(&mut self,
793 stack: &TraitObligationStack<'o, 'tcx>)
794 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
796 // Check for overflow.
798 let TraitObligationStack { obligation, .. } = *stack;
800 let mut candidates = SelectionCandidateSet {
805 // Other bounds. Consider both in-scope bounds from fn decl
806 // and applicable impls. There is a certain set of precedence rules here.
808 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
809 Some(ty::BoundCopy) => {
810 debug!("obligation self ty is {}",
811 obligation.predicate.0.self_ty().repr(self.tcx()));
813 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
815 try!(self.assemble_builtin_bound_candidates(ty::BoundCopy,
819 Some(bound @ ty::BoundSend) |
820 Some(bound @ ty::BoundSync) => {
821 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
823 // No explicit impls were declared for this type, consider the fallback rules.
824 if candidates.vec.is_empty() && !candidates.ambiguous {
825 try!(self.assemble_builtin_bound_candidates(bound, stack, &mut candidates));
829 Some(bound @ ty::BoundSized) => {
830 // Sized and Copy are always automatically computed.
831 try!(self.assemble_builtin_bound_candidates(bound, stack, &mut candidates));
835 // For the time being, we ignore user-defined impls for builtin-bounds, other than
837 // (And unboxed candidates only apply to the Fn/FnMut/etc traits.)
838 try!(self.assemble_closure_candidates(obligation, &mut candidates));
839 try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates));
840 try!(self.assemble_candidates_from_impls(obligation, &mut candidates));
841 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
845 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
846 try!(self.assemble_candidates_from_caller_bounds(stack, &mut candidates));
847 debug!("candidate list size: {}", candidates.vec.len());
851 fn assemble_candidates_from_projected_tys(&mut self,
852 obligation: &TraitObligation<'tcx>,
853 candidates: &mut SelectionCandidateSet<'tcx>)
855 let poly_trait_predicate =
856 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
858 debug!("assemble_candidates_for_projected_tys({},{})",
859 obligation.repr(self.tcx()),
860 poly_trait_predicate.repr(self.tcx()));
862 // FIXME(#20297) -- just examining the self-type is very simplistic
864 // before we go into the whole skolemization thing, just
865 // quickly check if the self-type is a projection at all.
866 let trait_def_id = match poly_trait_predicate.0.trait_ref.self_ty().sty {
867 ty::ty_projection(ref data) => data.trait_ref.def_id,
868 ty::ty_infer(ty::TyVar(_)) => {
869 // If the self-type is an inference variable, then it MAY wind up
870 // being a projected type, so induce an ambiguity.
872 // FIXME(#20297) -- being strict about this can cause
873 // inference failures with BorrowFrom, which is
874 // unfortunate. Can we do better here?
875 debug!("assemble_candidates_for_projected_tys: ambiguous self-type");
876 candidates.ambiguous = true;
882 debug!("assemble_candidates_for_projected_tys: trait_def_id={}",
883 trait_def_id.repr(self.tcx()));
885 let result = self.infcx.probe(|snapshot| {
886 self.match_projection_obligation_against_bounds_from_trait(obligation,
891 candidates.vec.push(ProjectionCandidate);
895 fn match_projection_obligation_against_bounds_from_trait(
897 obligation: &TraitObligation<'tcx>,
898 snapshot: &infer::CombinedSnapshot)
901 let poly_trait_predicate =
902 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
903 let (skol_trait_predicate, skol_map) =
904 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
905 debug!("match_projection_obligation_against_bounds_from_trait: \
906 skol_trait_predicate={} skol_map={}",
907 skol_trait_predicate.repr(self.tcx()),
908 skol_map.repr(self.tcx()));
910 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
911 ty::ty_projection(ref data) => &data.trait_ref,
913 self.tcx().sess.span_bug(
914 obligation.cause.span,
915 &format!("match_projection_obligation_against_bounds_from_trait() called \
916 but self-ty not a projection: {}",
917 skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())));
920 debug!("match_projection_obligation_against_bounds_from_trait: \
921 projection_trait_ref={}",
922 projection_trait_ref.repr(self.tcx()));
924 let trait_predicates = ty::lookup_predicates(self.tcx(), projection_trait_ref.def_id);
925 let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs);
926 debug!("match_projection_obligation_against_bounds_from_trait: \
928 bounds.repr(self.tcx()));
931 util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec())
934 |bound| self.infcx.probe(
935 |_| self.match_projection(obligation,
937 skol_trait_predicate.trait_ref.clone(),
941 debug!("match_projection_obligation_against_bounds_from_trait: \
943 matching_bound.repr(self.tcx()));
944 match matching_bound {
947 // Repeat the successful match, if any, this time outside of a probe.
948 let result = self.match_projection(obligation,
950 skol_trait_predicate.trait_ref.clone(),
959 fn match_projection(&mut self,
960 obligation: &TraitObligation<'tcx>,
961 trait_bound: ty::PolyTraitRef<'tcx>,
962 skol_trait_ref: Rc<ty::TraitRef<'tcx>>,
963 skol_map: &infer::SkolemizationMap,
964 snapshot: &infer::CombinedSnapshot)
967 assert!(!skol_trait_ref.has_escaping_regions());
968 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
969 match self.infcx.sub_poly_trait_refs(false,
972 ty::Binder(skol_trait_ref.clone())) {
974 Err(_) => { return false; }
977 self.infcx.leak_check(skol_map, snapshot).is_ok()
980 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
981 /// supplied to find out whether it is listed among them.
983 /// Never affects inference environment.
984 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
985 stack: &TraitObligationStack<'o, 'tcx>,
986 candidates: &mut SelectionCandidateSet<'tcx>)
987 -> Result<(),SelectionError<'tcx>>
989 debug!("assemble_candidates_from_caller_bounds({})",
990 stack.obligation.repr(self.tcx()));
992 let caller_trait_refs: Vec<_> =
993 self.param_env().caller_bounds.iter()
994 .filter_map(|o| o.to_opt_poly_trait_ref())
998 util::transitive_bounds(
999 self.tcx(), &caller_trait_refs[]);
1001 let matching_bounds =
1003 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1005 let param_candidates =
1006 matching_bounds.map(|bound| ParamCandidate(bound));
1008 candidates.vec.extend(param_candidates);
1013 fn evaluate_where_clause<'o>(&mut self,
1014 stack: &TraitObligationStack<'o, 'tcx>,
1015 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1016 -> EvaluationResult<'tcx>
1018 self.infcx().probe(move |_| {
1019 match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1020 Ok(obligations) => {
1021 self.evaluate_predicates_recursively(Some(stack), obligations.iter())
1024 EvaluatedToErr(Unimplemented)
1030 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1031 /// FnMut<..>` where `X` is a closure type.
1033 /// Note: the type parameters on a closure candidate are modeled as *output* type
1034 /// parameters and hence do not affect whether this trait is a match or not. They will be
1035 /// unified during the confirmation step.
1036 fn assemble_closure_candidates(&mut self,
1037 obligation: &TraitObligation<'tcx>,
1038 candidates: &mut SelectionCandidateSet<'tcx>)
1039 -> Result<(),SelectionError<'tcx>>
1041 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1043 None => { return Ok(()); }
1046 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1047 let (closure_def_id, substs) = match self_ty.sty {
1048 ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
1049 ty::ty_infer(ty::TyVar(_)) => {
1050 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1051 candidates.ambiguous = true;
1054 _ => { return Ok(()); }
1057 debug!("assemble_unboxed_candidates: self_ty={} kind={:?} obligation={}",
1058 self_ty.repr(self.tcx()),
1060 obligation.repr(self.tcx()));
1062 match self.closure_typer.closure_kind(closure_def_id) {
1063 Some(closure_kind) => {
1064 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1065 if closure_kind == kind {
1066 candidates.vec.push(ClosureCandidate(closure_def_id, substs.clone()));
1070 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1071 candidates.ambiguous = true;
1078 /// Implement one of the `Fn()` family for a fn pointer.
1079 fn assemble_fn_pointer_candidates(&mut self,
1080 obligation: &TraitObligation<'tcx>,
1081 candidates: &mut SelectionCandidateSet<'tcx>)
1082 -> Result<(),SelectionError<'tcx>>
1084 // We provide a `Fn` impl for fn pointers. There is no need to provide
1085 // the other traits (e.g. `FnMut`) since those are provided by blanket
1087 if Some(obligation.predicate.def_id()) != self.tcx().lang_items.fn_trait() {
1091 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1093 ty::ty_infer(ty::TyVar(_)) => {
1094 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1095 candidates.ambiguous = true; // could wind up being a fn() type
1098 // provide an impl, but only for suitable `fn` pointers
1099 ty::ty_bare_fn(_, &ty::BareFnTy {
1100 unsafety: ast::Unsafety::Normal,
1102 sig: ty::Binder(ty::FnSig {
1104 output: ty::FnConverging(_),
1108 candidates.vec.push(FnPointerCandidate);
1117 /// Search for impls that might apply to `obligation`.
1118 fn assemble_candidates_from_impls(&mut self,
1119 obligation: &TraitObligation<'tcx>,
1120 candidates: &mut SelectionCandidateSet<'tcx>)
1121 -> Result<(), SelectionError<'tcx>>
1123 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1124 debug!("assemble_candidates_from_impls(self_ty={})", self_ty.repr(self.tcx()));
1126 let all_impls = self.all_impls(obligation.predicate.def_id());
1127 for &impl_def_id in &all_impls {
1128 self.infcx.probe(|snapshot| {
1129 let (skol_obligation_trait_pred, skol_map) =
1130 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
1131 match self.match_impl(impl_def_id, obligation, snapshot,
1132 &skol_map, skol_obligation_trait_pred.trait_ref.clone()) {
1134 candidates.vec.push(ImplCandidate(impl_def_id));
1143 /// Search for impls that might apply to `obligation`.
1144 fn assemble_candidates_from_object_ty(&mut self,
1145 obligation: &TraitObligation<'tcx>,
1146 candidates: &mut SelectionCandidateSet<'tcx>)
1148 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1150 debug!("assemble_candidates_from_object_ty(self_ty={})",
1151 self_ty.repr(self.tcx()));
1153 // Object-safety candidates are only applicable to object-safe
1154 // traits. Including this check is useful because it helps
1155 // inference in cases of traits like `BorrowFrom`, which are
1156 // not object-safe, and which rely on being able to infer the
1157 // self-type from one of the other inputs. Without this check,
1158 // these cases wind up being considered ambiguous due to a
1159 // (spurious) ambiguity introduced here.
1160 if !object_safety::is_object_safe(self.tcx(), obligation.predicate.to_poly_trait_ref()) {
1164 let poly_trait_ref = match self_ty.sty {
1165 ty::ty_trait(ref data) => {
1166 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1168 ty::ty_infer(ty::TyVar(_)) => {
1169 debug!("assemble_candidates_from_object_ty: ambiguous");
1170 candidates.ambiguous = true; // could wind up being an object type
1178 debug!("assemble_candidates_from_object_ty: poly_trait_ref={}",
1179 poly_trait_ref.repr(self.tcx()));
1181 // see whether the object trait can be upcast to the trait we are looking for
1182 let obligation_def_id = obligation.predicate.def_id();
1183 let upcast_trait_ref = match util::upcast(self.tcx(), poly_trait_ref, obligation_def_id) {
1188 debug!("assemble_candidates_from_object_ty: upcast_trait_ref={}",
1189 upcast_trait_ref.repr(self.tcx()));
1191 // check whether the upcast version of the trait-ref matches what we are looking for
1192 if let Ok(()) = self.infcx.probe(|_| self.match_poly_trait_ref(obligation,
1193 upcast_trait_ref.clone())) {
1194 debug!("assemble_candidates_from_object_ty: matched, pushing candidate");
1195 candidates.vec.push(ObjectCandidate);
1199 ///////////////////////////////////////////////////////////////////////////
1202 // Winnowing is the process of attempting to resolve ambiguity by
1203 // probing further. During the winnowing process, we unify all
1204 // type variables (ignoring skolemization) and then we also
1205 // attempt to evaluate recursive bounds to see if they are
1208 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1209 /// obligations are met. Returns true if `candidate` remains viable after this further
1211 fn winnow_candidate<'o>(&mut self,
1212 stack: &TraitObligationStack<'o, 'tcx>,
1213 candidate: &SelectionCandidate<'tcx>)
1214 -> EvaluationResult<'tcx>
1216 debug!("winnow_candidate: candidate={}", candidate.repr(self.tcx()));
1217 let result = self.infcx.probe(|_| {
1218 let candidate = (*candidate).clone();
1219 match self.confirm_candidate(stack.obligation, candidate) {
1220 Ok(selection) => self.winnow_selection(Some(stack), selection),
1221 Err(error) => EvaluatedToErr(error),
1224 debug!("winnow_candidate depth={} result={:?}",
1225 stack.obligation.recursion_depth, result);
1229 fn winnow_selection<'o>(&mut self,
1230 stack: Option<&TraitObligationStack<'o, 'tcx>>,
1231 selection: Selection<'tcx>)
1232 -> EvaluationResult<'tcx>
1234 self.evaluate_predicates_recursively(stack, selection.iter_nested())
1237 /// Returns true if `candidate_i` should be dropped in favor of
1238 /// `candidate_j`. Generally speaking we will drop duplicate
1239 /// candidates and prefer where-clause candidates.
1240 fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
1241 candidate_i: &SelectionCandidate<'tcx>,
1242 candidate_j: &SelectionCandidate<'tcx>)
1245 if candidate_i == candidate_j {
1249 match (candidate_i, candidate_j) {
1250 (&ImplCandidate(..), &ParamCandidate(..)) |
1251 (&ClosureCandidate(..), &ParamCandidate(..)) |
1252 (&FnPointerCandidate(..), &ParamCandidate(..)) |
1253 (&BuiltinCandidate(..), &ParamCandidate(..)) => {
1254 // We basically prefer always prefer to use a
1255 // where-clause over another option. Where clauses
1256 // impose the burden of finding the exact match onto
1257 // the caller. Using an impl in preference of a where
1258 // clause can also lead us to "overspecialize", as in
1262 (&ProjectionCandidate, &ParamCandidate(_)) => {
1263 // FIXME(#20297) -- this gives where clauses precedent
1264 // over projections. Really these are just two means
1265 // of deducing information (one based on the where
1266 // clauses on the trait definition; one based on those
1267 // on the enclosing scope), and it'd be better to
1268 // integrate them more intelligently. But for now this
1269 // seems ok. If we DON'T give where clauses
1270 // precedence, we run into trouble in default methods,
1271 // where both the projection bounds for `Self::A` and
1272 // the where clauses are in scope.
1281 ///////////////////////////////////////////////////////////////////////////
1284 // These cover the traits that are built-in to the language
1285 // itself. This includes `Copy` and `Sized` for sure. For the
1286 // moment, it also includes `Send` / `Sync` and a few others, but
1287 // those will hopefully change to library-defined traits in the
1290 fn assemble_builtin_bound_candidates<'o>(&mut self,
1291 bound: ty::BuiltinBound,
1292 stack: &TraitObligationStack<'o, 'tcx>,
1293 candidates: &mut SelectionCandidateSet<'tcx>)
1294 -> Result<(),SelectionError<'tcx>>
1296 match self.builtin_bound(bound, stack.obligation) {
1298 debug!("builtin_bound: bound={}",
1299 bound.repr(self.tcx()));
1300 candidates.vec.push(BuiltinCandidate(bound));
1303 Ok(ParameterBuiltin) => { Ok(()) }
1304 Ok(AmbiguousBuiltin) => {
1305 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1306 Ok(candidates.ambiguous = true)
1308 Err(e) => { Err(e) }
1312 fn builtin_bound(&mut self,
1313 bound: ty::BuiltinBound,
1314 obligation: &TraitObligation<'tcx>)
1315 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1317 // Note: these tests operate on types that may contain bound
1318 // regions. To be proper, we ought to skolemize here, but we
1319 // forego the skolemization and defer it until the
1320 // confirmation step.
1322 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1323 return match self_ty.sty {
1324 ty::ty_infer(ty::IntVar(_)) |
1325 ty::ty_infer(ty::FloatVar(_)) |
1330 ty::ty_bare_fn(..) |
1332 // safe for everything
1336 ty::ty_uniq(referent_ty) => { // Box<T>
1348 Ok(If(vec![referent_ty]))
1353 ty::ty_ptr(..) => { // *const T, *mut T
1362 // sync and send are not implemented for *const, *mut
1368 ty::ty_trait(ref data) => {
1373 ty::BoundCopy | ty::BoundSync | ty::BoundSend => {
1374 if data.bounds.builtin_bounds.contains(&bound) {
1377 // Recursively check all supertraits to find out if any further
1378 // bounds are required and thus we must fulfill.
1380 data.principal_trait_ref_with_self_ty(self.tcx(),
1381 self.tcx().types.err);
1382 for tr in util::supertraits(self.tcx(), principal) {
1383 let td = ty::lookup_trait_def(self.tcx(), tr.def_id());
1384 if td.bounds.builtin_bounds.contains(&bound) {
1385 return Ok(If(Vec::new()))
1395 ty::ty_rptr(_, ty::mt { ty: referent_ty, mutbl }) => {
1400 // &mut T is affine and hence never `Copy`
1401 ast::MutMutable => {
1405 // &T is always copyable
1406 ast::MutImmutable => {
1418 Ok(If(vec![referent_ty]))
1423 ty::ty_vec(element_ty, ref len) => {
1429 // [T, ..n] is copy iff T is copy
1430 Ok(If(vec![element_ty]))
1433 // [T] is unsized and hence affine
1449 Ok(If(vec![element_ty]))
1455 // Equivalent to [u8]
1469 ty::ty_tup(ref tys) => {
1470 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1474 ty::ty_closure(def_id, _, substs) => {
1475 // FIXME -- This case is tricky. In the case of by-ref
1476 // closures particularly, we need the results of
1477 // inference to decide how to reflect the type of each
1478 // upvar (the upvar may have type `T`, but the runtime
1479 // type could be `&mut`, `&`, or just `T`). For now,
1480 // though, we'll do this unsoundly and assume that all
1481 // captures are by value. Really what we ought to do
1482 // is reserve judgement and then intertwine this
1483 // analysis with closure inference.
1484 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
1486 // Unboxed closures shouldn't be
1487 // implicitly copyable
1488 if bound == ty::BoundCopy {
1489 return Ok(ParameterBuiltin);
1492 // Upvars are always local variables or references to
1493 // local variables, and local variables cannot be
1494 // unsized, so the closure struct as a whole must be
1496 if bound == ty::BoundSized {
1497 return Ok(If(Vec::new()));
1500 match self.closure_typer.closure_upvars(def_id, substs) {
1502 Ok(If(upvars.iter().map(|c| c.ty).collect()))
1505 debug!("assemble_builtin_bound_candidates: no upvar types available yet");
1506 Ok(AmbiguousBuiltin)
1511 ty::ty_struct(def_id, substs) => {
1512 let types: Vec<Ty> =
1513 ty::struct_fields(self.tcx(), def_id, substs).iter()
1516 nominal(self, bound, def_id, types)
1519 ty::ty_enum(def_id, substs) => {
1520 let types: Vec<Ty> =
1521 ty::substd_enum_variants(self.tcx(), def_id, substs)
1523 .flat_map(|variant| variant.args.iter())
1526 nominal(self, bound, def_id, types)
1529 ty::ty_projection(_) |
1530 ty::ty_param(_) => {
1531 // Note: A type parameter is only considered to meet a
1532 // particular bound if there is a where clause telling
1533 // us that it does, and that case is handled by
1534 // `assemble_candidates_from_caller_bounds()`.
1535 Ok(ParameterBuiltin)
1538 ty::ty_infer(ty::TyVar(_)) => {
1539 // Unbound type variable. Might or might not have
1540 // applicable impls and so forth, depending on what
1541 // those type variables wind up being bound to.
1542 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1543 Ok(AmbiguousBuiltin)
1546 ty::ty_open(ty) => {
1547 // these only crop up in trans, and represent an
1548 // "opened" unsized/existential type (one that has
1549 // been dereferenced)
1566 ty::ty_infer(ty::FreshTy(_)) |
1567 ty::ty_infer(ty::FreshIntTy(_)) => {
1568 self.tcx().sess.bug(
1570 "asked to assemble builtin bounds of unexpected type: {}",
1571 self_ty.repr(self.tcx()))[]);
1575 fn nominal<'cx, 'tcx>(this: &mut SelectionContext<'cx, 'tcx>,
1576 bound: ty::BuiltinBound,
1578 types: Vec<Ty<'tcx>>)
1579 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1581 // First check for markers and other nonsense.
1582 let tcx = this.tcx();
1585 if Some(def_id) == tcx.lang_items.managed_bound() {
1586 return Err(Unimplemented)
1591 return Ok(ParameterBuiltin)
1596 Some(def_id) == tcx.lang_items.managed_bound() ||
1597 Some(def_id) == tcx.lang_items.unsafe_cell_type()
1599 return Err(Unimplemented)
1603 ty::BoundSized => { }
1610 ///////////////////////////////////////////////////////////////////////////
1613 // Confirmation unifies the output type parameters of the trait
1614 // with the values found in the obligation, possibly yielding a
1615 // type error. See `doc.rs` for more details.
1617 fn confirm_candidate(&mut self,
1618 obligation: &TraitObligation<'tcx>,
1619 candidate: SelectionCandidate<'tcx>)
1620 -> Result<Selection<'tcx>,SelectionError<'tcx>>
1622 debug!("confirm_candidate({}, {})",
1623 obligation.repr(self.tcx()),
1624 candidate.repr(self.tcx()));
1627 BuiltinCandidate(builtin_bound) => {
1629 try!(self.confirm_builtin_candidate(obligation, builtin_bound))))
1633 Ok(VtableBuiltin(VtableBuiltinData { nested: VecPerParamSpace::empty() }))
1636 ParamCandidate(param) => {
1637 let obligations = self.confirm_param_candidate(obligation, param);
1638 Ok(VtableParam(obligations))
1641 ImplCandidate(impl_def_id) => {
1643 try!(self.confirm_impl_candidate(obligation, impl_def_id));
1644 Ok(VtableImpl(vtable_impl))
1647 ClosureCandidate(closure_def_id, substs) => {
1648 try!(self.confirm_closure_candidate(obligation, closure_def_id, &substs));
1649 Ok(VtableClosure(closure_def_id, substs))
1652 ObjectCandidate => {
1653 let data = self.confirm_object_candidate(obligation);
1654 Ok(VtableObject(data))
1657 FnPointerCandidate => {
1659 try!(self.confirm_fn_pointer_candidate(obligation));
1660 Ok(VtableFnPointer(fn_type))
1663 ProjectionCandidate => {
1664 self.confirm_projection_candidate(obligation);
1665 Ok(VtableParam(Vec::new()))
1670 fn confirm_projection_candidate(&mut self,
1671 obligation: &TraitObligation<'tcx>)
1673 let _: Result<(),()> =
1674 self.infcx.try(|snapshot| {
1676 self.match_projection_obligation_against_bounds_from_trait(obligation,
1683 fn confirm_param_candidate(&mut self,
1684 obligation: &TraitObligation<'tcx>,
1685 param: ty::PolyTraitRef<'tcx>)
1686 -> Vec<PredicateObligation<'tcx>>
1688 debug!("confirm_param_candidate({},{})",
1689 obligation.repr(self.tcx()),
1690 param.repr(self.tcx()));
1692 // During evaluation, we already checked that this
1693 // where-clause trait-ref could be unified with the obligation
1694 // trait-ref. Repeat that unification now without any
1695 // transactional boundary; it should not fail.
1696 match self.match_where_clause_trait_ref(obligation, param.clone()) {
1697 Ok(obligations) => obligations,
1699 self.tcx().sess.bug(
1700 &format!("Where clause `{}` was applicable to `{}` but now is not",
1701 param.repr(self.tcx()),
1702 obligation.repr(self.tcx())));
1707 fn confirm_builtin_candidate(&mut self,
1708 obligation: &TraitObligation<'tcx>,
1709 bound: ty::BuiltinBound)
1710 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
1711 SelectionError<'tcx>>
1713 debug!("confirm_builtin_candidate({})",
1714 obligation.repr(self.tcx()));
1716 match try!(self.builtin_bound(bound, obligation)) {
1717 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
1718 AmbiguousBuiltin | ParameterBuiltin => {
1719 self.tcx().sess.span_bug(
1720 obligation.cause.span,
1721 &format!("builtin bound for {} was ambig",
1722 obligation.repr(self.tcx()))[]);
1727 fn vtable_builtin_data(&mut self,
1728 obligation: &TraitObligation<'tcx>,
1729 bound: ty::BuiltinBound,
1730 nested: Vec<Ty<'tcx>>)
1731 -> VtableBuiltinData<PredicateObligation<'tcx>>
1733 let derived_cause = self.derived_cause(obligation, BuiltinDerivedObligation);
1734 let obligations = nested.iter().map(|&bound_ty| {
1735 // the obligation might be higher-ranked, e.g. for<'a> &'a
1736 // int : Copy. In that case, we will wind up with
1737 // late-bound regions in the `nested` vector. So for each
1738 // one we instantiate to a skolemized region, do our work
1739 // to produce something like `&'0 int : Copy`, and then
1740 // re-bind it. This is a bit of busy-work but preserves
1741 // the invariant that we only manipulate free regions, not
1743 self.infcx.try(|snapshot| {
1744 let (skol_ty, skol_map) =
1745 self.infcx().skolemize_late_bound_regions(&ty::Binder(bound_ty), snapshot);
1746 let skol_predicate =
1747 util::predicate_for_builtin_bound(
1749 derived_cause.clone(),
1751 obligation.recursion_depth + 1,
1753 match skol_predicate {
1754 Ok(skol_predicate) => Ok(self.infcx().plug_leaks(skol_map, snapshot,
1756 Err(ErrorReported) => Err(ErrorReported)
1759 }).collect::<Result<_, _>>();
1760 let obligations = match obligations {
1762 Err(ErrorReported) => Vec::new()
1765 let obligations = VecPerParamSpace::new(obligations, Vec::new(), Vec::new());
1767 debug!("vtable_builtin_data: obligations={}",
1768 obligations.repr(self.tcx()));
1770 VtableBuiltinData { nested: obligations }
1773 fn confirm_impl_candidate(&mut self,
1774 obligation: &TraitObligation<'tcx>,
1775 impl_def_id: ast::DefId)
1776 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
1777 SelectionError<'tcx>>
1779 debug!("confirm_impl_candidate({},{})",
1780 obligation.repr(self.tcx()),
1781 impl_def_id.repr(self.tcx()));
1783 // First, create the substitutions by matching the impl again,
1784 // this time not in a probe.
1785 self.infcx.try(|snapshot| {
1786 let (skol_obligation_trait_ref, skol_map) =
1787 self.infcx().skolemize_late_bound_regions(&obligation.predicate, snapshot);
1789 self.rematch_impl(impl_def_id, obligation,
1790 snapshot, &skol_map, skol_obligation_trait_ref.trait_ref);
1791 debug!("confirm_impl_candidate substs={}", substs.repr(self.tcx()));
1792 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
1793 obligation.recursion_depth + 1, skol_map, snapshot))
1797 fn vtable_impl(&mut self,
1798 impl_def_id: ast::DefId,
1799 substs: Normalized<'tcx, Substs<'tcx>>,
1800 cause: ObligationCause<'tcx>,
1801 recursion_depth: uint,
1802 skol_map: infer::SkolemizationMap,
1803 snapshot: &infer::CombinedSnapshot)
1804 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
1806 debug!("vtable_impl(impl_def_id={}, substs={}, recursion_depth={}, skol_map={})",
1807 impl_def_id.repr(self.tcx()),
1808 substs.repr(self.tcx()),
1810 skol_map.repr(self.tcx()));
1812 let mut impl_obligations =
1813 self.impl_obligations(cause,
1820 debug!("vtable_impl: impl_def_id={} impl_obligations={}",
1821 impl_def_id.repr(self.tcx()),
1822 impl_obligations.repr(self.tcx()));
1824 impl_obligations.extend(TypeSpace, substs.obligations.into_iter());
1826 VtableImplData { impl_def_id: impl_def_id,
1827 substs: substs.value,
1828 nested: impl_obligations }
1831 fn confirm_object_candidate(&mut self,
1832 obligation: &TraitObligation<'tcx>)
1833 -> VtableObjectData<'tcx>
1835 debug!("confirm_object_candidate({})",
1836 obligation.repr(self.tcx()));
1838 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1839 let poly_trait_ref = match self_ty.sty {
1840 ty::ty_trait(ref data) => {
1841 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1844 self.tcx().sess.span_bug(obligation.cause.span,
1845 "object candidate with non-object");
1849 let obligation_def_id = obligation.predicate.def_id();
1850 let upcast_trait_ref = match util::upcast(self.tcx(),
1851 poly_trait_ref.clone(),
1852 obligation_def_id) {
1855 self.tcx().sess.span_bug(obligation.cause.span,
1856 &format!("unable to upcast from {} to {}",
1857 poly_trait_ref.repr(self.tcx()),
1858 obligation_def_id.repr(self.tcx())));
1862 match self.match_poly_trait_ref(obligation, upcast_trait_ref) {
1865 self.tcx().sess.span_bug(obligation.cause.span,
1866 "failed to match trait refs");
1870 VtableObjectData { object_ty: self_ty }
1873 fn confirm_fn_pointer_candidate(&mut self,
1874 obligation: &TraitObligation<'tcx>)
1875 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
1877 debug!("confirm_fn_pointer_candidate({})",
1878 obligation.repr(self.tcx()));
1880 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1881 let sig = ty::ty_fn_sig(self_ty);
1882 let ty::Binder((trait_ref, _)) =
1883 util::closure_trait_ref_and_return_type(self.tcx(),
1884 obligation.predicate.def_id(),
1887 util::TupleArgumentsFlag::Yes);
1888 let trait_ref = ty::Binder(trait_ref);
1890 try!(self.confirm_poly_trait_refs(obligation.cause.clone(),
1891 obligation.predicate.to_poly_trait_ref(),
1896 fn confirm_closure_candidate(&mut self,
1897 obligation: &TraitObligation<'tcx>,
1898 closure_def_id: ast::DefId,
1899 substs: &Substs<'tcx>)
1900 -> Result<(),SelectionError<'tcx>>
1902 debug!("confirm_closure_candidate({},{},{})",
1903 obligation.repr(self.tcx()),
1904 closure_def_id.repr(self.tcx()),
1905 substs.repr(self.tcx()));
1907 let trait_ref = self.closure_trait_ref(obligation,
1911 debug!("confirm_closure_candidate(closure_def_id={}, trait_ref={})",
1912 closure_def_id.repr(self.tcx()),
1913 trait_ref.repr(self.tcx()));
1915 self.confirm_poly_trait_refs(obligation.cause.clone(),
1916 obligation.predicate.to_poly_trait_ref(),
1920 /// In the case of closure types and fn pointers,
1921 /// we currently treat the input type parameters on the trait as
1922 /// outputs. This means that when we have a match we have only
1923 /// considered the self type, so we have to go back and make sure
1924 /// to relate the argument types too. This is kind of wrong, but
1925 /// since we control the full set of impls, also not that wrong,
1926 /// and it DOES yield better error messages (since we don't report
1927 /// errors as if there is no applicable impl, but rather report
1928 /// errors are about mismatched argument types.
1930 /// Here is an example. Imagine we have an closure expression
1931 /// and we desugared it so that the type of the expression is
1932 /// `Closure`, and `Closure` expects an int as argument. Then it
1933 /// is "as if" the compiler generated this impl:
1935 /// impl Fn(int) for Closure { ... }
1937 /// Now imagine our obligation is `Fn(uint) for Closure`. So far
1938 /// we have matched the self-type `Closure`. At this point we'll
1939 /// compare the `int` to `uint` and generate an error.
1941 /// Note that this checking occurs *after* the impl has selected,
1942 /// because these output type parameters should not affect the
1943 /// selection of the impl. Therefore, if there is a mismatch, we
1944 /// report an error to the user.
1945 fn confirm_poly_trait_refs(&mut self,
1946 obligation_cause: ObligationCause,
1947 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
1948 expected_trait_ref: ty::PolyTraitRef<'tcx>)
1949 -> Result<(), SelectionError<'tcx>>
1951 let origin = infer::RelateOutputImplTypes(obligation_cause.span);
1953 let obligation_trait_ref = obligation_trait_ref.clone();
1954 match self.infcx.sub_poly_trait_refs(false,
1956 expected_trait_ref.clone(),
1957 obligation_trait_ref.clone()) {
1959 Err(e) => Err(OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
1963 ///////////////////////////////////////////////////////////////////////////
1966 // Matching is a common path used for both evaluation and
1967 // confirmation. It basically unifies types that appear in impls
1968 // and traits. This does affect the surrounding environment;
1969 // therefore, when used during evaluation, match routines must be
1970 // run inside of a `probe()` so that their side-effects are
1973 fn rematch_impl(&mut self,
1974 impl_def_id: ast::DefId,
1975 obligation: &TraitObligation<'tcx>,
1976 snapshot: &infer::CombinedSnapshot,
1977 skol_map: &infer::SkolemizationMap,
1978 skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>)
1979 -> Normalized<'tcx, Substs<'tcx>>
1981 match self.match_impl(impl_def_id, obligation, snapshot,
1982 skol_map, skol_obligation_trait_ref) {
1987 self.tcx().sess.bug(
1988 &format!("Impl {} was matchable against {} but now is not",
1989 impl_def_id.repr(self.tcx()),
1990 obligation.repr(self.tcx()))[]);
1995 fn match_impl(&mut self,
1996 impl_def_id: ast::DefId,
1997 obligation: &TraitObligation<'tcx>,
1998 snapshot: &infer::CombinedSnapshot,
1999 skol_map: &infer::SkolemizationMap,
2000 skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>)
2001 -> Result<Normalized<'tcx, Substs<'tcx>>, ()>
2003 let impl_trait_ref = ty::impl_trait_ref(self.tcx(), impl_def_id).unwrap();
2005 // Before we create the substitutions and everything, first
2006 // consider a "quick reject". This avoids creating more types
2007 // and so forth that we need to.
2008 if self.fast_reject_trait_refs(obligation, &*impl_trait_ref) {
2012 let impl_substs = util::fresh_substs_for_impl(self.infcx,
2013 obligation.cause.span,
2016 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2019 let impl_trait_ref =
2020 project::normalize_with_depth(self,
2021 obligation.cause.clone(),
2022 obligation.recursion_depth + 1,
2025 debug!("match_impl(impl_def_id={}, obligation={}, \
2026 impl_trait_ref={}, skol_obligation_trait_ref={})",
2027 impl_def_id.repr(self.tcx()),
2028 obligation.repr(self.tcx()),
2029 impl_trait_ref.repr(self.tcx()),
2030 skol_obligation_trait_ref.repr(self.tcx()));
2032 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2033 match self.infcx.sub_trait_refs(false,
2035 impl_trait_ref.value.clone(),
2036 skol_obligation_trait_ref) {
2039 debug!("match_impl: failed sub_trait_refs due to `{}`",
2040 ty::type_err_to_str(self.tcx(), &e));
2045 match self.infcx.leak_check(skol_map, snapshot) {
2048 debug!("match_impl: failed leak check due to `{}`",
2049 ty::type_err_to_str(self.tcx(), &e));
2054 debug!("match_impl: success impl_substs={}", impl_substs.repr(self.tcx()));
2055 Ok(Normalized { value: impl_substs,
2056 obligations: impl_trait_ref.obligations })
2059 fn fast_reject_trait_refs(&mut self,
2060 obligation: &TraitObligation,
2061 impl_trait_ref: &ty::TraitRef)
2064 // We can avoid creating type variables and doing the full
2065 // substitution if we find that any of the input types, when
2066 // simplified, do not match.
2068 obligation.predicate.0.input_types().iter()
2069 .zip(impl_trait_ref.input_types().iter())
2070 .any(|(&obligation_ty, &impl_ty)| {
2071 let simplified_obligation_ty =
2072 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2073 let simplified_impl_ty =
2074 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2076 simplified_obligation_ty.is_some() &&
2077 simplified_impl_ty.is_some() &&
2078 simplified_obligation_ty != simplified_impl_ty
2082 /// Normalize `where_clause_trait_ref` and try to match it against
2083 /// `obligation`. If successful, return any predicates that
2084 /// result from the normalization. Normalization is necessary
2085 /// because where-clauses are stored in the parameter environment
2087 fn match_where_clause_trait_ref(&mut self,
2088 obligation: &TraitObligation<'tcx>,
2089 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2090 -> Result<Vec<PredicateObligation<'tcx>>,()>
2093 try!(self.match_poly_trait_ref(obligation, where_clause_trait_ref));
2098 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2099 /// obligation is satisfied.
2100 fn match_poly_trait_ref(&mut self,
2101 obligation: &TraitObligation<'tcx>,
2102 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2105 debug!("match_poly_trait_ref: obligation={} poly_trait_ref={}",
2106 obligation.repr(self.tcx()),
2107 poly_trait_ref.repr(self.tcx()));
2109 let origin = infer::RelateOutputImplTypes(obligation.cause.span);
2110 match self.infcx.sub_poly_trait_refs(false,
2113 obligation.predicate.to_poly_trait_ref()) {
2119 /// Determines whether the self type declared against
2120 /// `impl_def_id` matches `obligation_self_ty`. If successful,
2121 /// returns the substitutions used to make them match. See
2122 /// `match_impl()`. For example, if `impl_def_id` is declared
2125 /// impl<T:Copy> Foo for ~T { ... }
2127 /// and `obligation_self_ty` is `int`, we'd back an `Err(_)`
2128 /// result. But if `obligation_self_ty` were `~int`, we'd get
2129 /// back `Ok(T=int)`.
2130 fn match_inherent_impl(&mut self,
2131 impl_def_id: ast::DefId,
2132 obligation_cause: &ObligationCause,
2133 obligation_self_ty: Ty<'tcx>)
2134 -> Result<Substs<'tcx>,()>
2136 // Create fresh type variables for each type parameter declared
2138 let impl_substs = util::fresh_substs_for_impl(self.infcx,
2139 obligation_cause.span,
2142 // Find the self type for the impl.
2143 let impl_self_ty = ty::lookup_item_type(self.tcx(), impl_def_id).ty;
2144 let impl_self_ty = impl_self_ty.subst(self.tcx(), &impl_substs);
2146 debug!("match_impl_self_types(obligation_self_ty={}, impl_self_ty={})",
2147 obligation_self_ty.repr(self.tcx()),
2148 impl_self_ty.repr(self.tcx()));
2150 match self.match_self_types(obligation_cause,
2152 obligation_self_ty) {
2154 debug!("Matched impl_substs={}", impl_substs.repr(self.tcx()));
2164 fn match_self_types(&mut self,
2165 cause: &ObligationCause,
2167 // The self type provided by the impl/caller-obligation:
2168 provided_self_ty: Ty<'tcx>,
2170 // The self type the obligation is for:
2171 required_self_ty: Ty<'tcx>)
2174 // FIXME(#5781) -- equating the types is stronger than
2175 // necessary. Should consider variance of trait w/r/t Self.
2177 let origin = infer::RelateSelfType(cause.span);
2178 match self.infcx.eq_types(false,
2187 ///////////////////////////////////////////////////////////////////////////
2190 fn push_stack<'o,'s:'o>(&mut self,
2191 previous_stack: Option<&'s TraitObligationStack<'s, 'tcx>>,
2192 obligation: &'o TraitObligation<'tcx>)
2193 -> TraitObligationStack<'o, 'tcx>
2195 let fresh_trait_ref =
2196 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2198 TraitObligationStack {
2199 obligation: obligation,
2200 fresh_trait_ref: fresh_trait_ref,
2201 previous: previous_stack.map(|p| p), // FIXME variance
2205 /// Returns set of all impls for a given trait.
2206 fn all_impls(&self, trait_def_id: ast::DefId) -> Vec<ast::DefId> {
2207 ty::populate_implementations_for_trait_if_necessary(self.tcx(), trait_def_id);
2209 match self.tcx().trait_impls.borrow().get(&trait_def_id) {
2211 Some(impls) => impls.borrow().clone()
2215 fn closure_trait_ref(&self,
2216 obligation: &TraitObligation<'tcx>,
2217 closure_def_id: ast::DefId,
2218 substs: &Substs<'tcx>)
2219 -> ty::PolyTraitRef<'tcx>
2221 let closure_type = self.closure_typer.closure_type(closure_def_id, substs);
2222 let ty::Binder((trait_ref, _)) =
2223 util::closure_trait_ref_and_return_type(self.tcx(),
2224 obligation.predicate.def_id(),
2225 obligation.predicate.0.self_ty(), // (1)
2227 util::TupleArgumentsFlag::No);
2229 // (1) Feels icky to skip the binder here, but OTOH we know
2230 // that the self-type is an unboxed closure type and hence is
2231 // in fact unparameterized (or at least does not reference any
2232 // regions bound in the obligation). Still probably some
2233 // refactoring could make this nicer.
2235 ty::Binder(trait_ref)
2238 fn impl_obligations(&mut self,
2239 cause: ObligationCause<'tcx>,
2240 recursion_depth: uint,
2241 impl_def_id: ast::DefId,
2242 impl_substs: &Substs<'tcx>,
2243 skol_map: infer::SkolemizationMap,
2244 snapshot: &infer::CombinedSnapshot)
2245 -> VecPerParamSpace<PredicateObligation<'tcx>>
2247 let impl_bounds = ty::lookup_predicates(self.tcx(), impl_def_id);
2248 let bounds = impl_bounds.instantiate(self.tcx(), impl_substs);
2249 let normalized_bounds =
2250 project::normalize_with_depth(self, cause.clone(), recursion_depth, &bounds);
2251 let normalized_bounds =
2252 self.infcx().plug_leaks(skol_map, snapshot, &normalized_bounds);
2253 let mut impl_obligations =
2254 util::predicates_for_generics(self.tcx(),
2257 &normalized_bounds.value);
2258 impl_obligations.extend(TypeSpace, normalized_bounds.obligations.into_iter());
2262 #[allow(unused_comparisons)]
2263 fn derived_cause(&self,
2264 obligation: &TraitObligation<'tcx>,
2265 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2266 -> ObligationCause<'tcx>
2269 * Creates a cause for obligations that are derived from
2270 * `obligation` by a recursive search (e.g., for a builtin
2271 * bound, or eventually a `impl Foo for ..`). If `obligation`
2272 * is itself a derived obligation, this is just a clone, but
2273 * otherwise we create a "derived obligation" cause so as to
2274 * keep track of the original root obligation for error
2278 // NOTE(flaper87): As of now, it keeps track of the whole error
2279 // chain. Ideally, we should have a way to configure this either
2280 // by using -Z verbose or just a CLI argument.
2281 if obligation.recursion_depth >= 0 {
2282 let derived_cause = DerivedObligationCause {
2283 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2284 parent_code: Rc::new(obligation.cause.code.clone()),
2286 ObligationCause::new(obligation.cause.span,
2287 obligation.cause.body_id,
2288 variant(derived_cause))
2290 obligation.cause.clone()
2295 impl<'tcx> Repr<'tcx> for SelectionCandidate<'tcx> {
2296 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
2298 ErrorCandidate => format!("ErrorCandidate"),
2299 BuiltinCandidate(b) => format!("BuiltinCandidate({:?})", b),
2300 ParamCandidate(ref a) => format!("ParamCandidate({})", a.repr(tcx)),
2301 ImplCandidate(a) => format!("ImplCandidate({})", a.repr(tcx)),
2302 ProjectionCandidate => format!("ProjectionCandidate"),
2303 FnPointerCandidate => format!("FnPointerCandidate"),
2304 ObjectCandidate => {
2305 format!("ObjectCandidate")
2307 ClosureCandidate(c, ref s) => {
2308 format!("ClosureCandidate({:?},{})", c, s.repr(tcx))
2314 impl<'tcx> SelectionCache<'tcx> {
2315 pub fn new() -> SelectionCache<'tcx> {
2317 hashmap: RefCell::new(HashMap::new())
2322 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
2323 fn iter(&self) -> Option<&TraitObligationStack<'o, 'tcx>> {
2328 impl<'o, 'tcx> Iterator for Option<&'o TraitObligationStack<'o, 'tcx>> {
2329 type Item = &'o TraitObligationStack<'o,'tcx>;
2331 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
2344 impl<'o, 'tcx> Repr<'tcx> for TraitObligationStack<'o, 'tcx> {
2345 fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
2346 format!("TraitObligationStack({})",
2347 self.obligation.repr(tcx))
2351 impl<'tcx> EvaluationResult<'tcx> {
2352 fn may_apply(&self) -> bool {
2356 EvaluatedToErr(Overflow) |
2357 EvaluatedToErr(OutputTypeParameterMismatch(..)) => {
2360 EvaluatedToErr(Unimplemented) => {
2367 impl MethodMatchResult {
2368 pub fn may_apply(&self) -> bool {
2370 MethodMatched(_) => true,
2371 MethodAmbiguous(_) => true,
2372 MethodDidNotMatch => false,