]> git.proxmox.com Git - rustc.git/blob - src/librustc/traits/select.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / librustc / traits / select.rs
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.
4 //
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.
10
11 //! See `README.md` for high-level documentation
12
13 pub use self::MethodMatchResult::*;
14 pub use self::MethodMatchedData::*;
15 use self::SelectionCandidate::*;
16 use self::BuiltinBoundConditions::*;
17 use self::EvaluationResult::*;
18
19 use super::coherence;
20 use super::DerivedObligationCause;
21 use super::project;
22 use super::project::{normalize_with_depth, Normalized};
23 use super::{PredicateObligation, TraitObligation, ObligationCause};
24 use super::report_overflow_error;
25 use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
26 use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
27 use super::{ObjectCastObligation, Obligation};
28 use super::ProjectionMode;
29 use super::TraitNotObjectSafe;
30 use super::Selection;
31 use super::SelectionResult;
32 use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
33 VtableFnPointer, VtableObject, VtableDefaultImpl};
34 use super::{VtableImplData, VtableObjectData, VtableBuiltinData,
35 VtableClosureData, VtableDefaultImplData};
36 use super::object_safety;
37 use super::util;
38
39 use hir::def_id::DefId;
40 use infer;
41 use infer::{InferCtxt, InferOk, TypeFreshener, TypeOrigin};
42 use ty::subst::{Subst, Substs, TypeSpace};
43 use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
44 use traits;
45 use ty::fast_reject;
46 use ty::relate::TypeRelation;
47
48 use std::cell::RefCell;
49 use std::fmt;
50 use std::rc::Rc;
51 use syntax::abi::Abi;
52 use hir;
53 use util::common::ErrorReported;
54 use util::nodemap::FnvHashMap;
55
56 pub struct SelectionContext<'cx, 'tcx:'cx> {
57 infcx: &'cx InferCtxt<'cx, 'tcx>,
58
59 /// Freshener used specifically for skolemizing entries on the
60 /// obligation stack. This ensures that all entries on the stack
61 /// at one time will have the same set of skolemized entries,
62 /// which is important for checking for trait bounds that
63 /// recursively require themselves.
64 freshener: TypeFreshener<'cx, 'tcx>,
65
66 /// If true, indicates that the evaluation should be conservative
67 /// and consider the possibility of types outside this crate.
68 /// This comes up primarily when resolving ambiguity. Imagine
69 /// there is some trait reference `$0 : Bar` where `$0` is an
70 /// inference variable. If `intercrate` is true, then we can never
71 /// say for sure that this reference is not implemented, even if
72 /// there are *no impls at all for `Bar`*, because `$0` could be
73 /// bound to some type that in a downstream crate that implements
74 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
75 /// though, we set this to false, because we are only interested
76 /// in types that the user could actually have written --- in
77 /// other words, we consider `$0 : Bar` to be unimplemented if
78 /// there is no type that the user could *actually name* that
79 /// would satisfy it. This avoids crippling inference, basically.
80 intercrate: bool,
81 }
82
83 // A stack that walks back up the stack frame.
84 struct TraitObligationStack<'prev, 'tcx: 'prev> {
85 obligation: &'prev TraitObligation<'tcx>,
86
87 /// Trait ref from `obligation` but skolemized with the
88 /// selection-context's freshener. Used to check for recursion.
89 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
90
91 previous: TraitObligationStackList<'prev, 'tcx>,
92 }
93
94 #[derive(Clone)]
95 pub struct SelectionCache<'tcx> {
96 hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>,
97 SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
98 }
99
100 pub enum MethodMatchResult {
101 MethodMatched(MethodMatchedData),
102 MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>),
103 MethodDidNotMatch,
104 }
105
106 #[derive(Copy, Clone, Debug)]
107 pub enum MethodMatchedData {
108 // In the case of a precise match, we don't really need to store
109 // how the match was found. So don't.
110 PreciseMethodMatch,
111
112 // In the case of a coercion, we need to know the precise impl so
113 // that we can determine the type to which things were coerced.
114 CoerciveMethodMatch(/* impl we matched */ DefId)
115 }
116
117 /// The selection process begins by considering all impls, where
118 /// clauses, and so forth that might resolve an obligation. Sometimes
119 /// we'll be able to say definitively that (e.g.) an impl does not
120 /// apply to the obligation: perhaps it is defined for `usize` but the
121 /// obligation is for `int`. In that case, we drop the impl out of the
122 /// list. But the other cases are considered *candidates*.
123 ///
124 /// For selection to succeed, there must be exactly one matching
125 /// candidate. If the obligation is fully known, this is guaranteed
126 /// by coherence. However, if the obligation contains type parameters
127 /// or variables, there may be multiple such impls.
128 ///
129 /// It is not a real problem if multiple matching impls exist because
130 /// of type variables - it just means the obligation isn't sufficiently
131 /// elaborated. In that case we report an ambiguity, and the caller can
132 /// try again after more type information has been gathered or report a
133 /// "type annotations required" error.
134 ///
135 /// However, with type parameters, this can be a real problem - type
136 /// parameters don't unify with regular types, but they *can* unify
137 /// with variables from blanket impls, and (unless we know its bounds
138 /// will always be satisfied) picking the blanket impl will be wrong
139 /// for at least *some* substitutions. To make this concrete, if we have
140 ///
141 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
142 /// impl<T: fmt::Debug> AsDebug for T {
143 /// type Out = T;
144 /// fn debug(self) -> fmt::Debug { self }
145 /// }
146 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
147 ///
148 /// we can't just use the impl to resolve the <T as AsDebug> obligation
149 /// - a type from another crate (that doesn't implement fmt::Debug) could
150 /// implement AsDebug.
151 ///
152 /// Because where-clauses match the type exactly, multiple clauses can
153 /// only match if there are unresolved variables, and we can mostly just
154 /// report this ambiguity in that case. This is still a problem - we can't
155 /// *do anything* with ambiguities that involve only regions. This is issue
156 /// #21974.
157 ///
158 /// If a single where-clause matches and there are no inference
159 /// variables left, then it definitely matches and we can just select
160 /// it.
161 ///
162 /// In fact, we even select the where-clause when the obligation contains
163 /// inference variables. The can lead to inference making "leaps of logic",
164 /// for example in this situation:
165 ///
166 /// pub trait Foo<T> { fn foo(&self) -> T; }
167 /// impl<T> Foo<()> for T { fn foo(&self) { } }
168 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
169 ///
170 /// pub fn foo<T>(t: T) where T: Foo<bool> {
171 /// println!("{:?}", <T as Foo<_>>::foo(&t));
172 /// }
173 /// fn main() { foo(false); }
174 ///
175 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
176 /// impl and the where-clause. We select the where-clause and unify $0=bool,
177 /// so the program prints "false". However, if the where-clause is omitted,
178 /// the blanket impl is selected, we unify $0=(), and the program prints
179 /// "()".
180 ///
181 /// Exactly the same issues apply to projection and object candidates, except
182 /// that we can have both a projection candidate and a where-clause candidate
183 /// for the same obligation. In that case either would do (except that
184 /// different "leaps of logic" would occur if inference variables are
185 /// present), and we just pick the where-clause. This is, for example,
186 /// required for associated types to work in default impls, as the bounds
187 /// are visible both as projection bounds and as where-clauses from the
188 /// parameter environment.
189 #[derive(PartialEq,Eq,Debug,Clone)]
190 enum SelectionCandidate<'tcx> {
191 BuiltinCandidate(ty::BuiltinBound),
192 ParamCandidate(ty::PolyTraitRef<'tcx>),
193 ImplCandidate(DefId),
194 DefaultImplCandidate(DefId),
195 DefaultImplObjectCandidate(DefId),
196
197 /// This is a trait matching with a projected type as `Self`, and
198 /// we found an applicable bound in the trait definition.
199 ProjectionCandidate,
200
201 /// Implementation of a `Fn`-family trait by one of the
202 /// anonymous types generated for a `||` expression.
203 ClosureCandidate(/* closure */ DefId, &'tcx ty::ClosureSubsts<'tcx>),
204
205 /// Implementation of a `Fn`-family trait by one of the anonymous
206 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
207 FnPointerCandidate,
208
209 ObjectCandidate,
210
211 BuiltinObjectCandidate,
212
213 BuiltinUnsizeCandidate,
214 }
215
216 struct SelectionCandidateSet<'tcx> {
217 // a list of candidates that definitely apply to the current
218 // obligation (meaning: types unify).
219 vec: Vec<SelectionCandidate<'tcx>>,
220
221 // if this is true, then there were candidates that might or might
222 // not have applied, but we couldn't tell. This occurs when some
223 // of the input types are type variables, in which case there are
224 // various "builtin" rules that might or might not trigger.
225 ambiguous: bool,
226 }
227
228 #[derive(PartialEq,Eq,Debug,Clone)]
229 struct EvaluatedCandidate<'tcx> {
230 candidate: SelectionCandidate<'tcx>,
231 evaluation: EvaluationResult,
232 }
233
234 enum BuiltinBoundConditions<'tcx> {
235 If(ty::Binder<Vec<Ty<'tcx>>>),
236 ParameterBuiltin,
237 AmbiguousBuiltin
238 }
239
240 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
241 /// The result of trait evaluation. The order is important
242 /// here as the evaluation of a list is the maximum of the
243 /// evaluations.
244 enum EvaluationResult {
245 /// Evaluation successful
246 EvaluatedToOk,
247 /// Evaluation failed because of recursion - treated as ambiguous
248 EvaluatedToUnknown,
249 /// Evaluation is known to be ambiguous
250 EvaluatedToAmbig,
251 /// Evaluation failed
252 EvaluatedToErr,
253 }
254
255 #[derive(Clone)]
256 pub struct EvaluationCache<'tcx> {
257 hashmap: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>>
258 }
259
260 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
261 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
262 SelectionContext {
263 infcx: infcx,
264 freshener: infcx.freshener(),
265 intercrate: false,
266 }
267 }
268
269 pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
270 SelectionContext {
271 infcx: infcx,
272 freshener: infcx.freshener(),
273 intercrate: true,
274 }
275 }
276
277 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
278 self.infcx
279 }
280
281 pub fn tcx(&self) -> &'cx TyCtxt<'tcx> {
282 self.infcx.tcx
283 }
284
285 pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> {
286 self.infcx.param_env()
287 }
288
289 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
290 self.infcx
291 }
292
293 pub fn projection_mode(&self) -> ProjectionMode {
294 self.infcx.projection_mode()
295 }
296
297 ///////////////////////////////////////////////////////////////////////////
298 // Selection
299 //
300 // The selection phase tries to identify *how* an obligation will
301 // be resolved. For example, it will identify which impl or
302 // parameter bound is to be used. The process can be inconclusive
303 // if the self type in the obligation is not fully inferred. Selection
304 // can result in an error in one of two ways:
305 //
306 // 1. If no applicable impl or parameter bound can be found.
307 // 2. If the output type parameters in the obligation do not match
308 // those specified by the impl/bound. For example, if the obligation
309 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
310 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
311
312 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
313 /// type environment by performing unification.
314 pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
315 -> SelectionResult<'tcx, Selection<'tcx>> {
316 debug!("select({:?})", obligation);
317 assert!(!obligation.predicate.has_escaping_regions());
318
319 let dep_node = obligation.predicate.dep_node();
320 let _task = self.tcx().dep_graph.in_task(dep_node);
321
322 let stack = self.push_stack(TraitObligationStackList::empty(), obligation);
323 match self.candidate_from_obligation(&stack)? {
324 None => {
325 self.consider_unification_despite_ambiguity(obligation);
326 Ok(None)
327 }
328 Some(candidate) => Ok(Some(self.confirm_candidate(obligation, candidate)?)),
329 }
330 }
331
332 /// In the particular case of unboxed closure obligations, we can
333 /// sometimes do some amount of unification for the
334 /// argument/return types even though we can't yet fully match obligation.
335 /// The particular case we are interesting in is an obligation of the form:
336 ///
337 /// C : FnFoo<A>
338 ///
339 /// where `C` is an unboxed closure type and `FnFoo` is one of the
340 /// `Fn` traits. Because we know that users cannot write impls for closure types
341 /// themselves, the only way that `C : FnFoo` can fail to match is under two
342 /// conditions:
343 ///
344 /// 1. The closure kind for `C` is not yet known, because inference isn't complete.
345 /// 2. The closure kind for `C` *is* known, but doesn't match what is needed.
346 /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed.
347 ///
348 /// In either case, we always know what argument types are
349 /// expected by `C`, no matter what kind of `Fn` trait it
350 /// eventually matches. So we can go ahead and unify the argument
351 /// types, even though the end result is ambiguous.
352 ///
353 /// Note that this is safe *even if* the trait would never be
354 /// matched (case 2 above). After all, in that case, an error will
355 /// result, so it kind of doesn't matter what we do --- unifying
356 /// the argument types can only be helpful to the user, because
357 /// once they patch up the kind of closure that is expected, the
358 /// argment types won't really change.
359 fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligation<'tcx>) {
360 // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`?
361 match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
362 Some(_) => { }
363 None => { return; }
364 }
365
366 // Is the self-type a closure type? We ignore bindings here
367 // because if it is a closure type, it must be a closure type from
368 // within this current fn, and hence none of the higher-ranked
369 // lifetimes can appear inside the self-type.
370 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
371 let (closure_def_id, substs) = match self_ty.sty {
372 ty::TyClosure(id, ref substs) => (id, substs),
373 _ => { return; }
374 };
375 assert!(!substs.has_escaping_regions());
376
377 // It is OK to call the unnormalized variant here - this is only
378 // reached for TyClosure: Fn inputs where the closure kind is
379 // still unknown, which should only occur in typeck where the
380 // closure type is already normalized.
381 let closure_trait_ref = self.closure_trait_ref_unnormalized(obligation,
382 closure_def_id,
383 substs);
384
385 match self.confirm_poly_trait_refs(obligation.cause.clone(),
386 obligation.predicate.to_poly_trait_ref(),
387 closure_trait_ref) {
388 Ok(()) => { }
389 Err(_) => { /* Silently ignore errors. */ }
390 }
391 }
392
393 ///////////////////////////////////////////////////////////////////////////
394 // EVALUATION
395 //
396 // Tests whether an obligation can be selected or whether an impl
397 // can be applied to particular types. It skips the "confirmation"
398 // step and hence completely ignores output type parameters.
399 //
400 // The result is "true" if the obligation *may* hold and "false" if
401 // we can be sure it does not.
402
403 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
404 pub fn evaluate_obligation(&mut self,
405 obligation: &PredicateObligation<'tcx>)
406 -> bool
407 {
408 debug!("evaluate_obligation({:?})",
409 obligation);
410
411 self.infcx.probe(|_| {
412 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
413 .may_apply()
414 })
415 }
416
417 /// Evaluates whether the obligation `obligation` can be satisfied,
418 /// and returns `false` if not certain. However, this is not entirely
419 /// accurate if inference variables are involved.
420 pub fn evaluate_obligation_conservatively(&mut self,
421 obligation: &PredicateObligation<'tcx>)
422 -> bool
423 {
424 debug!("evaluate_obligation_conservatively({:?})",
425 obligation);
426
427 self.infcx.probe(|_| {
428 self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
429 == EvaluatedToOk
430 })
431 }
432
433 /// Evaluates the predicates in `predicates` recursively. Note that
434 /// this applies projections in the predicates, and therefore
435 /// is run within an inference probe.
436 fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
437 stack: TraitObligationStackList<'o, 'tcx>,
438 predicates: I)
439 -> EvaluationResult
440 where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
441 {
442 let mut result = EvaluatedToOk;
443 for obligation in predicates {
444 let eval = self.evaluate_predicate_recursively(stack, obligation);
445 debug!("evaluate_predicate_recursively({:?}) = {:?}",
446 obligation, eval);
447 match eval {
448 EvaluatedToErr => { return EvaluatedToErr; }
449 EvaluatedToAmbig => { result = EvaluatedToAmbig; }
450 EvaluatedToUnknown => {
451 if result < EvaluatedToUnknown {
452 result = EvaluatedToUnknown;
453 }
454 }
455 EvaluatedToOk => { }
456 }
457 }
458 result
459 }
460
461 fn evaluate_predicate_recursively<'o>(&mut self,
462 previous_stack: TraitObligationStackList<'o, 'tcx>,
463 obligation: &PredicateObligation<'tcx>)
464 -> EvaluationResult
465 {
466 debug!("evaluate_predicate_recursively({:?})",
467 obligation);
468
469 // Check the cache from the tcx of predicates that we know
470 // have been proven elsewhere. This cache only contains
471 // predicates that are global in scope and hence unaffected by
472 // the current environment.
473 if self.tcx().fulfilled_predicates.borrow().check_duplicate(&obligation.predicate) {
474 return EvaluatedToOk;
475 }
476
477 match obligation.predicate {
478 ty::Predicate::Trait(ref t) => {
479 assert!(!t.has_escaping_regions());
480 let obligation = obligation.with(t.clone());
481 self.evaluate_obligation_recursively(previous_stack, &obligation)
482 }
483
484 ty::Predicate::Equate(ref p) => {
485 // does this code ever run?
486 match self.infcx.equality_predicate(obligation.cause.span, p) {
487 Ok(InferOk { obligations, .. }) => {
488 // FIXME(#32730) propagate obligations
489 assert!(obligations.is_empty());
490 EvaluatedToOk
491 },
492 Err(_) => EvaluatedToErr
493 }
494 }
495
496 ty::Predicate::WellFormed(ty) => {
497 match ty::wf::obligations(self.infcx, obligation.cause.body_id,
498 ty, obligation.cause.span) {
499 Some(obligations) =>
500 self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
501 None =>
502 EvaluatedToAmbig,
503 }
504 }
505
506 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
507 // we do not consider region relationships when
508 // evaluating trait matches
509 EvaluatedToOk
510 }
511
512 ty::Predicate::ObjectSafe(trait_def_id) => {
513 if object_safety::is_object_safe(self.tcx(), trait_def_id) {
514 EvaluatedToOk
515 } else {
516 EvaluatedToErr
517 }
518 }
519
520 ty::Predicate::Projection(ref data) => {
521 let project_obligation = obligation.with(data.clone());
522 match project::poly_project_and_unify_type(self, &project_obligation) {
523 Ok(Some(subobligations)) => {
524 self.evaluate_predicates_recursively(previous_stack,
525 subobligations.iter())
526 }
527 Ok(None) => {
528 EvaluatedToAmbig
529 }
530 Err(_) => {
531 EvaluatedToErr
532 }
533 }
534 }
535 }
536 }
537
538 fn evaluate_obligation_recursively<'o>(&mut self,
539 previous_stack: TraitObligationStackList<'o, 'tcx>,
540 obligation: &TraitObligation<'tcx>)
541 -> EvaluationResult
542 {
543 debug!("evaluate_obligation_recursively({:?})",
544 obligation);
545
546 let stack = self.push_stack(previous_stack, obligation);
547 let fresh_trait_ref = stack.fresh_trait_ref;
548 if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) {
549 debug!("CACHE HIT: EVAL({:?})={:?}",
550 fresh_trait_ref,
551 result);
552 return result;
553 }
554
555 let result = self.evaluate_stack(&stack);
556
557 debug!("CACHE MISS: EVAL({:?})={:?}",
558 fresh_trait_ref,
559 result);
560 self.insert_evaluation_cache(fresh_trait_ref, result);
561
562 result
563 }
564
565 fn evaluate_stack<'o>(&mut self,
566 stack: &TraitObligationStack<'o, 'tcx>)
567 -> EvaluationResult
568 {
569 // In intercrate mode, whenever any of the types are unbound,
570 // there can always be an impl. Even if there are no impls in
571 // this crate, perhaps the type would be unified with
572 // something from another crate that does provide an impl.
573 //
574 // In intra mode, we must still be conservative. The reason is
575 // that we want to avoid cycles. Imagine an impl like:
576 //
577 // impl<T:Eq> Eq for Vec<T>
578 //
579 // and a trait reference like `$0 : Eq` where `$0` is an
580 // unbound variable. When we evaluate this trait-reference, we
581 // will unify `$0` with `Vec<$1>` (for some fresh variable
582 // `$1`), on the condition that `$1 : Eq`. We will then wind
583 // up with many candidates (since that are other `Eq` impls
584 // that apply) and try to winnow things down. This results in
585 // a recursive evaluation that `$1 : Eq` -- as you can
586 // imagine, this is just where we started. To avoid that, we
587 // check for unbound variables and return an ambiguous (hence possible)
588 // match if we've seen this trait before.
589 //
590 // This suffices to allow chains like `FnMut` implemented in
591 // terms of `Fn` etc, but we could probably make this more
592 // precise still.
593 let input_types = stack.fresh_trait_ref.0.input_types();
594 let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh());
595 if unbound_input_types && self.intercrate {
596 debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
597 stack.fresh_trait_ref);
598 return EvaluatedToAmbig;
599 }
600 if unbound_input_types &&
601 stack.iter().skip(1).any(
602 |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref,
603 &prev.fresh_trait_ref))
604 {
605 debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
606 stack.fresh_trait_ref);
607 return EvaluatedToUnknown;
608 }
609
610 // If there is any previous entry on the stack that precisely
611 // matches this obligation, then we can assume that the
612 // obligation is satisfied for now (still all other conditions
613 // must be met of course). One obvious case this comes up is
614 // marker traits like `Send`. Think of a linked list:
615 //
616 // struct List<T> { data: T, next: Option<Box<List<T>>> {
617 //
618 // `Box<List<T>>` will be `Send` if `T` is `Send` and
619 // `Option<Box<List<T>>>` is `Send`, and in turn
620 // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
621 // `Send`.
622 //
623 // Note that we do this comparison using the `fresh_trait_ref`
624 // fields. Because these have all been skolemized using
625 // `self.freshener`, we can be sure that (a) this will not
626 // affect the inferencer state and (b) that if we see two
627 // skolemized types with the same index, they refer to the
628 // same unbound type variable.
629 if
630 stack.iter()
631 .skip(1) // skip top-most frame
632 .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref)
633 {
634 debug!("evaluate_stack({:?}) --> recursive",
635 stack.fresh_trait_ref);
636 return EvaluatedToOk;
637 }
638
639 match self.candidate_from_obligation(stack) {
640 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
641 Ok(None) => EvaluatedToAmbig,
642 Err(..) => EvaluatedToErr
643 }
644 }
645
646 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
647 /// obligations are met. Returns true if `candidate` remains viable after this further
648 /// scrutiny.
649 fn evaluate_candidate<'o>(&mut self,
650 stack: &TraitObligationStack<'o, 'tcx>,
651 candidate: &SelectionCandidate<'tcx>)
652 -> EvaluationResult
653 {
654 debug!("evaluate_candidate: depth={} candidate={:?}",
655 stack.obligation.recursion_depth, candidate);
656 let result = self.infcx.probe(|_| {
657 let candidate = (*candidate).clone();
658 match self.confirm_candidate(stack.obligation, candidate) {
659 Ok(selection) => {
660 self.evaluate_predicates_recursively(
661 stack.list(),
662 selection.nested_obligations().iter())
663 }
664 Err(..) => EvaluatedToErr
665 }
666 });
667 debug!("evaluate_candidate: depth={} result={:?}",
668 stack.obligation.recursion_depth, result);
669 result
670 }
671
672 fn pick_evaluation_cache(&self) -> &EvaluationCache<'tcx> {
673 // see comment in `pick_candidate_cache`
674 if self.intercrate ||
675 !self.param_env().caller_bounds.is_empty()
676 {
677 &self.param_env().evaluation_cache
678 } else
679 {
680 &self.tcx().evaluation_cache
681 }
682 }
683
684 fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>)
685 -> Option<EvaluationResult>
686 {
687 let cache = self.pick_evaluation_cache();
688 cache.hashmap.borrow().get(&trait_ref).cloned()
689 }
690
691 fn insert_evaluation_cache(&mut self,
692 trait_ref: ty::PolyTraitRef<'tcx>,
693 result: EvaluationResult)
694 {
695 // Avoid caching results that depend on more than just the trait-ref:
696 // The stack can create EvaluatedToUnknown, and closure signatures
697 // being yet uninferred can create "spurious" EvaluatedToAmbig
698 // and EvaluatedToOk.
699 if result == EvaluatedToUnknown ||
700 ((result == EvaluatedToAmbig || result == EvaluatedToOk)
701 && trait_ref.has_closure_types())
702 {
703 return;
704 }
705
706 let cache = self.pick_evaluation_cache();
707 cache.hashmap.borrow_mut().insert(trait_ref, result);
708 }
709
710 ///////////////////////////////////////////////////////////////////////////
711 // CANDIDATE ASSEMBLY
712 //
713 // The selection process begins by examining all in-scope impls,
714 // caller obligations, and so forth and assembling a list of
715 // candidates. See `README.md` and the `Candidate` type for more
716 // details.
717
718 fn candidate_from_obligation<'o>(&mut self,
719 stack: &TraitObligationStack<'o, 'tcx>)
720 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
721 {
722 // Watch out for overflow. This intentionally bypasses (and does
723 // not update) the cache.
724 let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
725 if stack.obligation.recursion_depth >= recursion_limit {
726 report_overflow_error(self.infcx(), &stack.obligation, true);
727 }
728
729 // Check the cache. Note that we skolemize the trait-ref
730 // separately rather than using `stack.fresh_trait_ref` -- this
731 // is because we want the unbound variables to be replaced
732 // with fresh skolemized types starting from index 0.
733 let cache_fresh_trait_pred =
734 self.infcx.freshen(stack.obligation.predicate.clone());
735 debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
736 cache_fresh_trait_pred,
737 stack);
738 assert!(!stack.obligation.predicate.has_escaping_regions());
739
740 match self.check_candidate_cache(&cache_fresh_trait_pred) {
741 Some(c) => {
742 debug!("CACHE HIT: SELECT({:?})={:?}",
743 cache_fresh_trait_pred,
744 c);
745 return c;
746 }
747 None => { }
748 }
749
750 // If no match, compute result and insert into cache.
751 let candidate = self.candidate_from_obligation_no_cache(stack);
752
753 if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) {
754 debug!("CACHE MISS: SELECT({:?})={:?}",
755 cache_fresh_trait_pred, candidate);
756 self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone());
757 }
758
759 candidate
760 }
761
762 // Treat negative impls as unimplemented
763 fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
764 -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
765 if let ImplCandidate(def_id) = candidate {
766 if self.tcx().trait_impl_polarity(def_id) == Some(hir::ImplPolarity::Negative) {
767 return Err(Unimplemented)
768 }
769 }
770 Ok(Some(candidate))
771 }
772
773 fn candidate_from_obligation_no_cache<'o>(&mut self,
774 stack: &TraitObligationStack<'o, 'tcx>)
775 -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
776 {
777 if stack.obligation.predicate.references_error() {
778 // If we encounter a `TyError`, we generally prefer the
779 // most "optimistic" result in response -- that is, the
780 // one least likely to report downstream errors. But
781 // because this routine is shared by coherence and by
782 // trait selection, there isn't an obvious "right" choice
783 // here in that respect, so we opt to just return
784 // ambiguity and let the upstream clients sort it out.
785 return Ok(None);
786 }
787
788 if !self.is_knowable(stack) {
789 debug!("coherence stage: not knowable");
790 return Ok(None);
791 }
792
793 let candidate_set = self.assemble_candidates(stack)?;
794
795 if candidate_set.ambiguous {
796 debug!("candidate set contains ambig");
797 return Ok(None);
798 }
799
800 let mut candidates = candidate_set.vec;
801
802 debug!("assembled {} candidates for {:?}: {:?}",
803 candidates.len(),
804 stack,
805 candidates);
806
807 // At this point, we know that each of the entries in the
808 // candidate set is *individually* applicable. Now we have to
809 // figure out if they contain mutual incompatibilities. This
810 // frequently arises if we have an unconstrained input type --
811 // for example, we are looking for $0:Eq where $0 is some
812 // unconstrained type variable. In that case, we'll get a
813 // candidate which assumes $0 == int, one that assumes $0 ==
814 // usize, etc. This spells an ambiguity.
815
816 // If there is more than one candidate, first winnow them down
817 // by considering extra conditions (nested obligations and so
818 // forth). We don't winnow if there is exactly one
819 // candidate. This is a relatively minor distinction but it
820 // can lead to better inference and error-reporting. An
821 // example would be if there was an impl:
822 //
823 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
824 //
825 // and we were to see some code `foo.push_clone()` where `boo`
826 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
827 // we were to winnow, we'd wind up with zero candidates.
828 // Instead, we select the right impl now but report `Bar does
829 // not implement Clone`.
830 if candidates.len() == 1 {
831 return self.filter_negative_impls(candidates.pop().unwrap());
832 }
833
834 // Winnow, but record the exact outcome of evaluation, which
835 // is needed for specialization.
836 let mut candidates: Vec<_> = candidates.into_iter().filter_map(|c| {
837 let eval = self.evaluate_candidate(stack, &c);
838 if eval.may_apply() {
839 Some(EvaluatedCandidate {
840 candidate: c,
841 evaluation: eval,
842 })
843 } else {
844 None
845 }
846 }).collect();
847
848 // If there are STILL multiple candidate, we can further
849 // reduce the list by dropping duplicates -- including
850 // resolving specializations.
851 if candidates.len() > 1 {
852 let mut i = 0;
853 while i < candidates.len() {
854 let is_dup =
855 (0..candidates.len())
856 .filter(|&j| i != j)
857 .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
858 &candidates[j]));
859 if is_dup {
860 debug!("Dropping candidate #{}/{}: {:?}",
861 i, candidates.len(), candidates[i]);
862 candidates.swap_remove(i);
863 } else {
864 debug!("Retaining candidate #{}/{}: {:?}",
865 i, candidates.len(), candidates[i]);
866 i += 1;
867 }
868 }
869 }
870
871 // If there are *STILL* multiple candidates, give up and
872 // report ambiguity.
873 if candidates.len() > 1 {
874 debug!("multiple matches, ambig");
875 return Ok(None);
876 }
877
878 // If there are *NO* candidates, then there are no impls --
879 // that we know of, anyway. Note that in the case where there
880 // are unbound type variables within the obligation, it might
881 // be the case that you could still satisfy the obligation
882 // from another crate by instantiating the type variables with
883 // a type from another crate that does have an impl. This case
884 // is checked for in `evaluate_stack` (and hence users
885 // who might care about this case, like coherence, should use
886 // that function).
887 if candidates.is_empty() {
888 return Err(Unimplemented);
889 }
890
891 // Just one candidate left.
892 self.filter_negative_impls(candidates.pop().unwrap().candidate)
893 }
894
895 fn is_knowable<'o>(&mut self,
896 stack: &TraitObligationStack<'o, 'tcx>)
897 -> bool
898 {
899 debug!("is_knowable(intercrate={})", self.intercrate);
900
901 if !self.intercrate {
902 return true;
903 }
904
905 let obligation = &stack.obligation;
906 let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
907
908 // ok to skip binder because of the nature of the
909 // trait-ref-is-knowable check, which does not care about
910 // bound regions
911 let trait_ref = &predicate.skip_binder().trait_ref;
912
913 coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
914 }
915
916 fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
917 // If there are any where-clauses in scope, then we always use
918 // a cache local to this particular scope. Otherwise, we
919 // switch to a global cache. We used to try and draw
920 // finer-grained distinctions, but that led to a serious of
921 // annoying and weird bugs like #22019 and #18290. This simple
922 // rule seems to be pretty clearly safe and also still retains
923 // a very high hit rate (~95% when compiling rustc).
924 if !self.param_env().caller_bounds.is_empty() {
925 return &self.param_env().selection_cache;
926 }
927
928 // Avoid using the master cache during coherence and just rely
929 // on the local cache. This effectively disables caching
930 // during coherence. It is really just a simplification to
931 // avoid us having to fear that coherence results "pollute"
932 // the master cache. Since coherence executes pretty quickly,
933 // it's not worth going to more trouble to increase the
934 // hit-rate I don't think.
935 if self.intercrate {
936 return &self.param_env().selection_cache;
937 }
938
939 // Otherwise, we can use the global cache.
940 &self.tcx().selection_cache
941 }
942
943 fn check_candidate_cache(&mut self,
944 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
945 -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
946 {
947 let cache = self.pick_candidate_cache();
948 let hashmap = cache.hashmap.borrow();
949 hashmap.get(&cache_fresh_trait_pred.0.trait_ref).cloned()
950 }
951
952 fn insert_candidate_cache(&mut self,
953 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
954 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
955 {
956 let cache = self.pick_candidate_cache();
957 let mut hashmap = cache.hashmap.borrow_mut();
958 hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
959 }
960
961 fn should_update_candidate_cache(&mut self,
962 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
963 candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>)
964 -> bool
965 {
966 // In general, it's a good idea to cache results, even
967 // ambiguous ones, to save us some trouble later. But we have
968 // to be careful not to cache results that could be
969 // invalidated later by advances in inference. Normally, this
970 // is not an issue, because any inference variables whose
971 // types are not yet bound are "freshened" in the cache key,
972 // which means that if we later get the same request once that
973 // type variable IS bound, we'll have a different cache key.
974 // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is
975 // not yet known, we may cache the result as `None`. But if
976 // later `_#0t` is bound to `Bar`, then when we freshen we'll
977 // have `Vec<Bar> : Foo` as the cache key.
978 //
979 // HOWEVER, it CAN happen that we get an ambiguity result in
980 // one particular case around closures where the cache key
981 // would not change. That is when the precise types of the
982 // upvars that a closure references have not yet been figured
983 // out (i.e., because it is not yet known if they are captured
984 // by ref, and if by ref, what kind of ref). In these cases,
985 // when matching a builtin bound, we will yield back an
986 // ambiguous result. But the *cache key* is just the closure type,
987 // it doesn't capture the state of the upvar computation.
988 //
989 // To avoid this trap, just don't cache ambiguous results if
990 // the self-type contains no inference byproducts (that really
991 // shouldn't happen in other circumstances anyway, given
992 // coherence).
993
994 match *candidate {
995 Ok(Some(_)) | Err(_) => true,
996 Ok(None) => {
997 cache_fresh_trait_pred.0.trait_ref.substs.types.has_infer_types()
998 }
999 }
1000 }
1001
1002 fn assemble_candidates<'o>(&mut self,
1003 stack: &TraitObligationStack<'o, 'tcx>)
1004 -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
1005 {
1006 let TraitObligationStack { obligation, .. } = *stack;
1007 let ref obligation = Obligation {
1008 cause: obligation.cause.clone(),
1009 recursion_depth: obligation.recursion_depth,
1010 predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
1011 };
1012
1013 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1014 // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`).
1015 //
1016 // This is somewhat problematic, as the current scheme can't really
1017 // handle it turning to be a projection. This does end up as truly
1018 // ambiguous in most cases anyway.
1019 //
1020 // Until this is fixed, take the fast path out - this also improves
1021 // performance by preventing assemble_candidates_from_impls from
1022 // matching every impl for this trait.
1023 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
1024 }
1025
1026 let mut candidates = SelectionCandidateSet {
1027 vec: Vec::new(),
1028 ambiguous: false
1029 };
1030
1031 // Other bounds. Consider both in-scope bounds from fn decl
1032 // and applicable impls. There is a certain set of precedence rules here.
1033
1034 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1035 Some(ty::BoundCopy) => {
1036 debug!("obligation self ty is {:?}",
1037 obligation.predicate.0.self_ty());
1038
1039 // User-defined copy impls are permitted, but only for
1040 // structs and enums.
1041 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1042
1043 // For other types, we'll use the builtin rules.
1044 self.assemble_builtin_bound_candidates(ty::BoundCopy,
1045 obligation,
1046 &mut candidates)?;
1047 }
1048 Some(bound @ ty::BoundSized) => {
1049 // Sized is never implementable by end-users, it is
1050 // always automatically computed.
1051 self.assemble_builtin_bound_candidates(bound,
1052 obligation,
1053 &mut candidates)?;
1054 }
1055
1056 None if self.tcx().lang_items.unsize_trait() ==
1057 Some(obligation.predicate.def_id()) => {
1058 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1059 }
1060
1061 Some(ty::BoundSend) |
1062 Some(ty::BoundSync) |
1063 None => {
1064 self.assemble_closure_candidates(obligation, &mut candidates)?;
1065 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1066 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1067 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1068 }
1069 }
1070
1071 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1072 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1073 // Default implementations have lower priority, so we only
1074 // consider triggering a default if there is no other impl that can apply.
1075 if candidates.vec.is_empty() {
1076 self.assemble_candidates_from_default_impls(obligation, &mut candidates)?;
1077 }
1078 debug!("candidate list size: {}", candidates.vec.len());
1079 Ok(candidates)
1080 }
1081
1082 fn assemble_candidates_from_projected_tys(&mut self,
1083 obligation: &TraitObligation<'tcx>,
1084 candidates: &mut SelectionCandidateSet<'tcx>)
1085 {
1086 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1087
1088 // FIXME(#20297) -- just examining the self-type is very simplistic
1089
1090 // before we go into the whole skolemization thing, just
1091 // quickly check if the self-type is a projection at all.
1092 let trait_def_id = match obligation.predicate.0.trait_ref.self_ty().sty {
1093 ty::TyProjection(ref data) => data.trait_ref.def_id,
1094 ty::TyInfer(ty::TyVar(_)) => {
1095 span_bug!(obligation.cause.span,
1096 "Self=_ should have been handled by assemble_candidates");
1097 }
1098 _ => { return; }
1099 };
1100
1101 debug!("assemble_candidates_for_projected_tys: trait_def_id={:?}",
1102 trait_def_id);
1103
1104 let result = self.infcx.probe(|snapshot| {
1105 self.match_projection_obligation_against_bounds_from_trait(obligation,
1106 snapshot)
1107 });
1108
1109 if result {
1110 candidates.vec.push(ProjectionCandidate);
1111 }
1112 }
1113
1114 fn match_projection_obligation_against_bounds_from_trait(
1115 &mut self,
1116 obligation: &TraitObligation<'tcx>,
1117 snapshot: &infer::CombinedSnapshot)
1118 -> bool
1119 {
1120 let poly_trait_predicate =
1121 self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
1122 let (skol_trait_predicate, skol_map) =
1123 self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot);
1124 debug!("match_projection_obligation_against_bounds_from_trait: \
1125 skol_trait_predicate={:?} skol_map={:?}",
1126 skol_trait_predicate,
1127 skol_map);
1128
1129 let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty {
1130 ty::TyProjection(ref data) => &data.trait_ref,
1131 _ => {
1132 span_bug!(
1133 obligation.cause.span,
1134 "match_projection_obligation_against_bounds_from_trait() called \
1135 but self-ty not a projection: {:?}",
1136 skol_trait_predicate.trait_ref.self_ty());
1137 }
1138 };
1139 debug!("match_projection_obligation_against_bounds_from_trait: \
1140 projection_trait_ref={:?}",
1141 projection_trait_ref);
1142
1143 let trait_predicates = self.tcx().lookup_predicates(projection_trait_ref.def_id);
1144 let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs);
1145 debug!("match_projection_obligation_against_bounds_from_trait: \
1146 bounds={:?}",
1147 bounds);
1148
1149 let matching_bound =
1150 util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec())
1151 .filter_to_traits()
1152 .find(
1153 |bound| self.infcx.probe(
1154 |_| self.match_projection(obligation,
1155 bound.clone(),
1156 skol_trait_predicate.trait_ref.clone(),
1157 &skol_map,
1158 snapshot)));
1159
1160 debug!("match_projection_obligation_against_bounds_from_trait: \
1161 matching_bound={:?}",
1162 matching_bound);
1163 match matching_bound {
1164 None => false,
1165 Some(bound) => {
1166 // Repeat the successful match, if any, this time outside of a probe.
1167 let result = self.match_projection(obligation,
1168 bound,
1169 skol_trait_predicate.trait_ref.clone(),
1170 &skol_map,
1171 snapshot);
1172 assert!(result);
1173 true
1174 }
1175 }
1176 }
1177
1178 fn match_projection(&mut self,
1179 obligation: &TraitObligation<'tcx>,
1180 trait_bound: ty::PolyTraitRef<'tcx>,
1181 skol_trait_ref: ty::TraitRef<'tcx>,
1182 skol_map: &infer::SkolemizationMap,
1183 snapshot: &infer::CombinedSnapshot)
1184 -> bool
1185 {
1186 assert!(!skol_trait_ref.has_escaping_regions());
1187 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
1188 match self.infcx.sub_poly_trait_refs(false,
1189 origin,
1190 trait_bound.clone(),
1191 ty::Binder(skol_trait_ref.clone())) {
1192 Ok(InferOk { obligations, .. }) => {
1193 // FIXME(#32730) propagate obligations
1194 assert!(obligations.is_empty());
1195 }
1196 Err(_) => { return false; }
1197 }
1198
1199 self.infcx.leak_check(skol_map, snapshot).is_ok()
1200 }
1201
1202 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1203 /// supplied to find out whether it is listed among them.
1204 ///
1205 /// Never affects inference environment.
1206 fn assemble_candidates_from_caller_bounds<'o>(&mut self,
1207 stack: &TraitObligationStack<'o, 'tcx>,
1208 candidates: &mut SelectionCandidateSet<'tcx>)
1209 -> Result<(),SelectionError<'tcx>>
1210 {
1211 debug!("assemble_candidates_from_caller_bounds({:?})",
1212 stack.obligation);
1213
1214 let all_bounds =
1215 self.param_env().caller_bounds
1216 .iter()
1217 .filter_map(|o| o.to_opt_poly_trait_ref());
1218
1219 let matching_bounds =
1220 all_bounds.filter(
1221 |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply());
1222
1223 let param_candidates =
1224 matching_bounds.map(|bound| ParamCandidate(bound));
1225
1226 candidates.vec.extend(param_candidates);
1227
1228 Ok(())
1229 }
1230
1231 fn evaluate_where_clause<'o>(&mut self,
1232 stack: &TraitObligationStack<'o, 'tcx>,
1233 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
1234 -> EvaluationResult
1235 {
1236 self.infcx().probe(move |_| {
1237 match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1238 Ok(obligations) => {
1239 self.evaluate_predicates_recursively(stack.list(), obligations.iter())
1240 }
1241 Err(()) => EvaluatedToErr
1242 }
1243 })
1244 }
1245
1246 /// Check for the artificial impl that the compiler will create for an obligation like `X :
1247 /// FnMut<..>` where `X` is a closure type.
1248 ///
1249 /// Note: the type parameters on a closure candidate are modeled as *output* type
1250 /// parameters and hence do not affect whether this trait is a match or not. They will be
1251 /// unified during the confirmation step.
1252 fn assemble_closure_candidates(&mut self,
1253 obligation: &TraitObligation<'tcx>,
1254 candidates: &mut SelectionCandidateSet<'tcx>)
1255 -> Result<(),SelectionError<'tcx>>
1256 {
1257 let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) {
1258 Some(k) => k,
1259 None => { return Ok(()); }
1260 };
1261
1262 // ok to skip binder because the substs on closure types never
1263 // touch bound regions, they just capture the in-scope
1264 // type/region parameters
1265 let self_ty = *obligation.self_ty().skip_binder();
1266 let (closure_def_id, substs) = match self_ty.sty {
1267 ty::TyClosure(id, ref substs) => (id, substs),
1268 ty::TyInfer(ty::TyVar(_)) => {
1269 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
1270 candidates.ambiguous = true;
1271 return Ok(());
1272 }
1273 _ => { return Ok(()); }
1274 };
1275
1276 debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}",
1277 self_ty,
1278 kind,
1279 obligation);
1280
1281 match self.infcx.closure_kind(closure_def_id) {
1282 Some(closure_kind) => {
1283 debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
1284 if closure_kind.extends(kind) {
1285 candidates.vec.push(ClosureCandidate(closure_def_id, substs));
1286 }
1287 }
1288 None => {
1289 debug!("assemble_unboxed_candidates: closure_kind not yet known");
1290 candidates.ambiguous = true;
1291 }
1292 }
1293
1294 Ok(())
1295 }
1296
1297 /// Implement one of the `Fn()` family for a fn pointer.
1298 fn assemble_fn_pointer_candidates(&mut self,
1299 obligation: &TraitObligation<'tcx>,
1300 candidates: &mut SelectionCandidateSet<'tcx>)
1301 -> Result<(),SelectionError<'tcx>>
1302 {
1303 // We provide impl of all fn traits for fn pointers.
1304 if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
1305 return Ok(());
1306 }
1307
1308 // ok to skip binder because what we are inspecting doesn't involve bound regions
1309 let self_ty = *obligation.self_ty().skip_binder();
1310 match self_ty.sty {
1311 ty::TyInfer(ty::TyVar(_)) => {
1312 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
1313 candidates.ambiguous = true; // could wind up being a fn() type
1314 }
1315
1316 // provide an impl, but only for suitable `fn` pointers
1317 ty::TyFnDef(_, _, &ty::BareFnTy {
1318 unsafety: hir::Unsafety::Normal,
1319 abi: Abi::Rust,
1320 sig: ty::Binder(ty::FnSig {
1321 inputs: _,
1322 output: ty::FnConverging(_),
1323 variadic: false
1324 })
1325 }) |
1326 ty::TyFnPtr(&ty::BareFnTy {
1327 unsafety: hir::Unsafety::Normal,
1328 abi: Abi::Rust,
1329 sig: ty::Binder(ty::FnSig {
1330 inputs: _,
1331 output: ty::FnConverging(_),
1332 variadic: false
1333 })
1334 }) => {
1335 candidates.vec.push(FnPointerCandidate);
1336 }
1337
1338 _ => { }
1339 }
1340
1341 Ok(())
1342 }
1343
1344 /// Search for impls that might apply to `obligation`.
1345 fn assemble_candidates_from_impls(&mut self,
1346 obligation: &TraitObligation<'tcx>,
1347 candidates: &mut SelectionCandidateSet<'tcx>)
1348 -> Result<(), SelectionError<'tcx>>
1349 {
1350 debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
1351
1352 let def = self.tcx().lookup_trait_def(obligation.predicate.def_id());
1353
1354 def.for_each_relevant_impl(
1355 self.tcx(),
1356 obligation.predicate.0.trait_ref.self_ty(),
1357 |impl_def_id| {
1358 self.infcx.probe(|snapshot| {
1359 if let Ok(_) = self.match_impl(impl_def_id, obligation, snapshot) {
1360 candidates.vec.push(ImplCandidate(impl_def_id));
1361 }
1362 });
1363 }
1364 );
1365
1366 Ok(())
1367 }
1368
1369 fn assemble_candidates_from_default_impls(&mut self,
1370 obligation: &TraitObligation<'tcx>,
1371 candidates: &mut SelectionCandidateSet<'tcx>)
1372 -> Result<(), SelectionError<'tcx>>
1373 {
1374 // OK to skip binder here because the tests we do below do not involve bound regions
1375 let self_ty = *obligation.self_ty().skip_binder();
1376 debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty);
1377
1378 let def_id = obligation.predicate.def_id();
1379
1380 if self.tcx().trait_has_default_impl(def_id) {
1381 match self_ty.sty {
1382 ty::TyTrait(..) => {
1383 // For object types, we don't know what the closed
1384 // over types are. For most traits, this means we
1385 // conservatively say nothing; a candidate may be
1386 // added by `assemble_candidates_from_object_ty`.
1387 // However, for the kind of magic reflect trait,
1388 // we consider it to be implemented even for
1389 // object types, because it just lets you reflect
1390 // onto the object type, not into the object's
1391 // interior.
1392 if self.tcx().has_attr(def_id, "rustc_reflect_like") {
1393 candidates.vec.push(DefaultImplObjectCandidate(def_id));
1394 }
1395 }
1396 ty::TyParam(..) |
1397 ty::TyProjection(..) => {
1398 // In these cases, we don't know what the actual
1399 // type is. Therefore, we cannot break it down
1400 // into its constituent types. So we don't
1401 // consider the `..` impl but instead just add no
1402 // candidates: this means that typeck will only
1403 // succeed if there is another reason to believe
1404 // that this obligation holds. That could be a
1405 // where-clause or, in the case of an object type,
1406 // it could be that the object type lists the
1407 // trait (e.g. `Foo+Send : Send`). See
1408 // `compile-fail/typeck-default-trait-impl-send-param.rs`
1409 // for an example of a test case that exercises
1410 // this path.
1411 }
1412 ty::TyInfer(ty::TyVar(_)) => {
1413 // the defaulted impl might apply, we don't know
1414 candidates.ambiguous = true;
1415 }
1416 _ => {
1417 candidates.vec.push(DefaultImplCandidate(def_id.clone()))
1418 }
1419 }
1420 }
1421
1422 Ok(())
1423 }
1424
1425 /// Search for impls that might apply to `obligation`.
1426 fn assemble_candidates_from_object_ty(&mut self,
1427 obligation: &TraitObligation<'tcx>,
1428 candidates: &mut SelectionCandidateSet<'tcx>)
1429 {
1430 debug!("assemble_candidates_from_object_ty(self_ty={:?})",
1431 obligation.self_ty().skip_binder());
1432
1433 // Object-safety candidates are only applicable to object-safe
1434 // traits. Including this check is useful because it helps
1435 // inference in cases of traits like `BorrowFrom`, which are
1436 // not object-safe, and which rely on being able to infer the
1437 // self-type from one of the other inputs. Without this check,
1438 // these cases wind up being considered ambiguous due to a
1439 // (spurious) ambiguity introduced here.
1440 let predicate_trait_ref = obligation.predicate.to_poly_trait_ref();
1441 if !object_safety::is_object_safe(self.tcx(), predicate_trait_ref.def_id()) {
1442 return;
1443 }
1444
1445 self.infcx.commit_if_ok(|snapshot| {
1446 let (self_ty, _) =
1447 self.infcx().skolemize_late_bound_regions(&obligation.self_ty(), snapshot);
1448 let poly_trait_ref = match self_ty.sty {
1449 ty::TyTrait(ref data) => {
1450 match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) {
1451 Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => {
1452 if data.bounds.builtin_bounds.contains(&bound) {
1453 debug!("assemble_candidates_from_object_ty: matched builtin bound, \
1454 pushing candidate");
1455 candidates.vec.push(BuiltinObjectCandidate);
1456 return Ok(());
1457 }
1458 }
1459 _ => {}
1460 }
1461
1462 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
1463 }
1464 ty::TyInfer(ty::TyVar(_)) => {
1465 debug!("assemble_candidates_from_object_ty: ambiguous");
1466 candidates.ambiguous = true; // could wind up being an object type
1467 return Ok(());
1468 }
1469 _ => {
1470 return Ok(());
1471 }
1472 };
1473
1474 debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
1475 poly_trait_ref);
1476
1477 // Count only those upcast versions that match the trait-ref
1478 // we are looking for. Specifically, do not only check for the
1479 // correct trait, but also the correct type parameters.
1480 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
1481 // but `Foo` is declared as `trait Foo : Bar<u32>`.
1482 let upcast_trait_refs =
1483 util::supertraits(self.tcx(), poly_trait_ref)
1484 .filter(|upcast_trait_ref| {
1485 self.infcx.probe(|_| {
1486 let upcast_trait_ref = upcast_trait_ref.clone();
1487 self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
1488 })
1489 })
1490 .count();
1491
1492 if upcast_trait_refs > 1 {
1493 // can be upcast in many ways; need more type information
1494 candidates.ambiguous = true;
1495 } else if upcast_trait_refs == 1 {
1496 candidates.vec.push(ObjectCandidate);
1497 }
1498
1499 Ok::<(),()>(())
1500 }).unwrap();
1501 }
1502
1503 /// Search for unsizing that might apply to `obligation`.
1504 fn assemble_candidates_for_unsizing(&mut self,
1505 obligation: &TraitObligation<'tcx>,
1506 candidates: &mut SelectionCandidateSet<'tcx>) {
1507 // We currently never consider higher-ranked obligations e.g.
1508 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
1509 // because they are a priori invalid, and we could potentially add support
1510 // for them later, it's just that there isn't really a strong need for it.
1511 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
1512 // impl, and those are generally applied to concrete types.
1513 //
1514 // That said, one might try to write a fn with a where clause like
1515 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
1516 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
1517 // Still, you'd be more likely to write that where clause as
1518 // T: Trait
1519 // so it seems ok if we (conservatively) fail to accept that `Unsize`
1520 // obligation above. Should be possible to extend this in the future.
1521 let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) {
1522 Some(t) => t,
1523 None => {
1524 // Don't add any candidates if there are bound regions.
1525 return;
1526 }
1527 };
1528 let target = obligation.predicate.0.input_types()[0];
1529
1530 debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
1531 source, target);
1532
1533 let may_apply = match (&source.sty, &target.sty) {
1534 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
1535 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
1536 // Upcasts permit two things:
1537 //
1538 // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
1539 // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
1540 //
1541 // Note that neither of these changes requires any
1542 // change at runtime. Eventually this will be
1543 // generalized.
1544 //
1545 // We always upcast when we can because of reason
1546 // #2 (region bounds).
1547 data_a.principal.def_id() == data_a.principal.def_id() &&
1548 data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds)
1549 }
1550
1551 // T -> Trait.
1552 (_, &ty::TyTrait(_)) => true,
1553
1554 // Ambiguous handling is below T -> Trait, because inference
1555 // variables can still implement Unsize<Trait> and nested
1556 // obligations will have the final say (likely deferred).
1557 (&ty::TyInfer(ty::TyVar(_)), _) |
1558 (_, &ty::TyInfer(ty::TyVar(_))) => {
1559 debug!("assemble_candidates_for_unsizing: ambiguous");
1560 candidates.ambiguous = true;
1561 false
1562 }
1563
1564 // [T; n] -> [T].
1565 (&ty::TyArray(_, _), &ty::TySlice(_)) => true,
1566
1567 // Struct<T> -> Struct<U>.
1568 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
1569 def_id_a == def_id_b
1570 }
1571
1572 _ => false
1573 };
1574
1575 if may_apply {
1576 candidates.vec.push(BuiltinUnsizeCandidate);
1577 }
1578 }
1579
1580 ///////////////////////////////////////////////////////////////////////////
1581 // WINNOW
1582 //
1583 // Winnowing is the process of attempting to resolve ambiguity by
1584 // probing further. During the winnowing process, we unify all
1585 // type variables (ignoring skolemization) and then we also
1586 // attempt to evaluate recursive bounds to see if they are
1587 // satisfied.
1588
1589 /// Returns true if `candidate_i` should be dropped in favor of
1590 /// `candidate_j`. Generally speaking we will drop duplicate
1591 /// candidates and prefer where-clause candidates.
1592 /// Returns true if `victim` should be dropped in favor of
1593 /// `other`. Generally speaking we will drop duplicate
1594 /// candidates and prefer where-clause candidates.
1595 ///
1596 /// See the comment for "SelectionCandidate" for more details.
1597 fn candidate_should_be_dropped_in_favor_of<'o>(
1598 &mut self,
1599 victim: &EvaluatedCandidate<'tcx>,
1600 other: &EvaluatedCandidate<'tcx>)
1601 -> bool
1602 {
1603 if victim.candidate == other.candidate {
1604 return true;
1605 }
1606
1607 match other.candidate {
1608 ObjectCandidate |
1609 ParamCandidate(_) | ProjectionCandidate => match victim.candidate {
1610 DefaultImplCandidate(..) => {
1611 bug!(
1612 "default implementations shouldn't be recorded \
1613 when there are other valid candidates");
1614 }
1615 ImplCandidate(..) |
1616 ClosureCandidate(..) |
1617 FnPointerCandidate |
1618 BuiltinObjectCandidate |
1619 BuiltinUnsizeCandidate |
1620 DefaultImplObjectCandidate(..) |
1621 BuiltinCandidate(..) => {
1622 // We have a where-clause so don't go around looking
1623 // for impls.
1624 true
1625 }
1626 ObjectCandidate |
1627 ProjectionCandidate => {
1628 // Arbitrarily give param candidates priority
1629 // over projection and object candidates.
1630 true
1631 },
1632 ParamCandidate(..) => false,
1633 },
1634 ImplCandidate(other_def) => {
1635 // See if we can toss out `victim` based on specialization.
1636 // This requires us to know *for sure* that the `other` impl applies
1637 // i.e. EvaluatedToOk:
1638 if other.evaluation == EvaluatedToOk {
1639 if let ImplCandidate(victim_def) = victim.candidate {
1640 return traits::specializes(self.tcx(), other_def, victim_def);
1641 }
1642 }
1643
1644 false
1645 },
1646 _ => false
1647 }
1648 }
1649
1650 ///////////////////////////////////////////////////////////////////////////
1651 // BUILTIN BOUNDS
1652 //
1653 // These cover the traits that are built-in to the language
1654 // itself. This includes `Copy` and `Sized` for sure. For the
1655 // moment, it also includes `Send` / `Sync` and a few others, but
1656 // those will hopefully change to library-defined traits in the
1657 // future.
1658
1659 fn assemble_builtin_bound_candidates<'o>(&mut self,
1660 bound: ty::BuiltinBound,
1661 obligation: &TraitObligation<'tcx>,
1662 candidates: &mut SelectionCandidateSet<'tcx>)
1663 -> Result<(),SelectionError<'tcx>>
1664 {
1665 match self.builtin_bound(bound, obligation) {
1666 Ok(If(..)) => {
1667 debug!("builtin_bound: bound={:?}",
1668 bound);
1669 candidates.vec.push(BuiltinCandidate(bound));
1670 Ok(())
1671 }
1672 Ok(ParameterBuiltin) => { Ok(()) }
1673 Ok(AmbiguousBuiltin) => {
1674 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1675 Ok(candidates.ambiguous = true)
1676 }
1677 Err(e) => { Err(e) }
1678 }
1679 }
1680
1681 fn builtin_bound(&mut self,
1682 bound: ty::BuiltinBound,
1683 obligation: &TraitObligation<'tcx>)
1684 -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>>
1685 {
1686 // Note: these tests operate on types that may contain bound
1687 // regions. To be proper, we ought to skolemize here, but we
1688 // forego the skolemization and defer it until the
1689 // confirmation step.
1690
1691 let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty());
1692 return match self_ty.sty {
1693 ty::TyInfer(ty::IntVar(_)) |
1694 ty::TyInfer(ty::FloatVar(_)) |
1695 ty::TyUint(_) |
1696 ty::TyInt(_) |
1697 ty::TyBool |
1698 ty::TyFloat(_) |
1699 ty::TyFnDef(..) |
1700 ty::TyFnPtr(_) |
1701 ty::TyChar => {
1702 // safe for everything
1703 ok_if(Vec::new())
1704 }
1705
1706 ty::TyBox(_) => { // Box<T>
1707 match bound {
1708 ty::BoundCopy => Err(Unimplemented),
1709
1710 ty::BoundSized => ok_if(Vec::new()),
1711
1712 ty::BoundSync | ty::BoundSend => {
1713 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1714 }
1715 }
1716 }
1717
1718 ty::TyRawPtr(..) => { // *const T, *mut T
1719 match bound {
1720 ty::BoundCopy | ty::BoundSized => ok_if(Vec::new()),
1721
1722 ty::BoundSync | ty::BoundSend => {
1723 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1724 }
1725 }
1726 }
1727
1728 ty::TyTrait(ref data) => {
1729 match bound {
1730 ty::BoundSized => Err(Unimplemented),
1731 ty::BoundCopy => {
1732 if data.bounds.builtin_bounds.contains(&bound) {
1733 ok_if(Vec::new())
1734 } else {
1735 // Recursively check all supertraits to find out if any further
1736 // bounds are required and thus we must fulfill.
1737 let principal =
1738 data.principal_trait_ref_with_self_ty(self.tcx(),
1739 self.tcx().types.err);
1740 let copy_def_id = obligation.predicate.def_id();
1741 for tr in util::supertraits(self.tcx(), principal) {
1742 if tr.def_id() == copy_def_id {
1743 return ok_if(Vec::new())
1744 }
1745 }
1746
1747 Err(Unimplemented)
1748 }
1749 }
1750 ty::BoundSync | ty::BoundSend => {
1751 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1752 }
1753 }
1754 }
1755
1756 ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => {
1757 // &mut T or &T
1758 match bound {
1759 ty::BoundCopy => {
1760 match mutbl {
1761 // &mut T is affine and hence never `Copy`
1762 hir::MutMutable => Err(Unimplemented),
1763
1764 // &T is always copyable
1765 hir::MutImmutable => ok_if(Vec::new()),
1766 }
1767 }
1768
1769 ty::BoundSized => ok_if(Vec::new()),
1770
1771 ty::BoundSync | ty::BoundSend => {
1772 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1773 }
1774 }
1775 }
1776
1777 ty::TyArray(element_ty, _) => {
1778 // [T; n]
1779 match bound {
1780 ty::BoundCopy => ok_if(vec![element_ty]),
1781 ty::BoundSized => ok_if(Vec::new()),
1782 ty::BoundSync | ty::BoundSend => {
1783 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1784 }
1785 }
1786 }
1787
1788 ty::TyStr | ty::TySlice(_) => {
1789 match bound {
1790 ty::BoundSync | ty::BoundSend => {
1791 bug!("Send/Sync shouldn't occur in builtin_bounds()");
1792 }
1793
1794 ty::BoundCopy | ty::BoundSized => Err(Unimplemented),
1795 }
1796 }
1797
1798 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1799 ty::TyTuple(ref tys) => ok_if(tys.clone()),
1800
1801 ty::TyClosure(_, ref substs) => {
1802 // FIXME -- This case is tricky. In the case of by-ref
1803 // closures particularly, we need the results of
1804 // inference to decide how to reflect the type of each
1805 // upvar (the upvar may have type `T`, but the runtime
1806 // type could be `&mut`, `&`, or just `T`). For now,
1807 // though, we'll do this unsoundly and assume that all
1808 // captures are by value. Really what we ought to do
1809 // is reserve judgement and then intertwine this
1810 // analysis with closure inference.
1811
1812 // Unboxed closures shouldn't be
1813 // implicitly copyable
1814 if bound == ty::BoundCopy {
1815 return Ok(ParameterBuiltin);
1816 }
1817
1818 // Upvars are always local variables or references to
1819 // local variables, and local variables cannot be
1820 // unsized, so the closure struct as a whole must be
1821 // Sized.
1822 if bound == ty::BoundSized {
1823 return ok_if(Vec::new());
1824 }
1825
1826 ok_if(substs.upvar_tys.clone())
1827 }
1828
1829 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1830 let types: Vec<Ty> = def.all_fields().map(|f| {
1831 f.ty(self.tcx(), substs)
1832 }).collect();
1833 nominal(bound, types)
1834 }
1835
1836 ty::TyProjection(_) | ty::TyParam(_) => {
1837 // Note: A type parameter is only considered to meet a
1838 // particular bound if there is a where clause telling
1839 // us that it does, and that case is handled by
1840 // `assemble_candidates_from_caller_bounds()`.
1841 Ok(ParameterBuiltin)
1842 }
1843
1844 ty::TyInfer(ty::TyVar(_)) => {
1845 // Unbound type variable. Might or might not have
1846 // applicable impls and so forth, depending on what
1847 // those type variables wind up being bound to.
1848 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
1849 Ok(AmbiguousBuiltin)
1850 }
1851
1852 ty::TyError => ok_if(Vec::new()),
1853
1854 ty::TyInfer(ty::FreshTy(_))
1855 | ty::TyInfer(ty::FreshIntTy(_))
1856 | ty::TyInfer(ty::FreshFloatTy(_)) => {
1857 bug!("asked to assemble builtin bounds of unexpected type: {:?}",
1858 self_ty);
1859 }
1860 };
1861
1862 fn ok_if<'tcx>(v: Vec<Ty<'tcx>>)
1863 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> {
1864 Ok(If(ty::Binder(v)))
1865 }
1866
1867 fn nominal<'cx, 'tcx>(bound: ty::BuiltinBound,
1868 types: Vec<Ty<'tcx>>)
1869 -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>>
1870 {
1871 // First check for markers and other nonsense.
1872 match bound {
1873 // Fallback to whatever user-defined impls exist in this case.
1874 ty::BoundCopy => Ok(ParameterBuiltin),
1875
1876 // Sized if all the component types are sized.
1877 ty::BoundSized => ok_if(types),
1878
1879 // Shouldn't be coming through here.
1880 ty::BoundSend | ty::BoundSync => bug!(),
1881 }
1882 }
1883 }
1884
1885 /// For default impls, we need to break apart a type into its
1886 /// "constituent types" -- meaning, the types that it contains.
1887 ///
1888 /// Here are some (simple) examples:
1889 ///
1890 /// ```
1891 /// (i32, u32) -> [i32, u32]
1892 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
1893 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
1894 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
1895 /// ```
1896 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
1897 match t.sty {
1898 ty::TyUint(_) |
1899 ty::TyInt(_) |
1900 ty::TyBool |
1901 ty::TyFloat(_) |
1902 ty::TyFnDef(..) |
1903 ty::TyFnPtr(_) |
1904 ty::TyStr |
1905 ty::TyError |
1906 ty::TyInfer(ty::IntVar(_)) |
1907 ty::TyInfer(ty::FloatVar(_)) |
1908 ty::TyChar => {
1909 Vec::new()
1910 }
1911
1912 ty::TyTrait(..) |
1913 ty::TyParam(..) |
1914 ty::TyProjection(..) |
1915 ty::TyInfer(ty::TyVar(_)) |
1916 ty::TyInfer(ty::FreshTy(_)) |
1917 ty::TyInfer(ty::FreshIntTy(_)) |
1918 ty::TyInfer(ty::FreshFloatTy(_)) => {
1919 bug!("asked to assemble constituent types of unexpected type: {:?}",
1920 t);
1921 }
1922
1923 ty::TyBox(referent_ty) => { // Box<T>
1924 vec![referent_ty]
1925 }
1926
1927 ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
1928 ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
1929 vec![element_ty]
1930 },
1931
1932 ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => {
1933 vec![element_ty]
1934 }
1935
1936 ty::TyTuple(ref tys) => {
1937 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
1938 tys.clone()
1939 }
1940
1941 ty::TyClosure(_, ref substs) => {
1942 // FIXME(#27086). We are invariant w/r/t our
1943 // substs.func_substs, but we don't see them as
1944 // constituent types; this seems RIGHT but also like
1945 // something that a normal type couldn't simulate. Is
1946 // this just a gap with the way that PhantomData and
1947 // OIBIT interact? That is, there is no way to say
1948 // "make me invariant with respect to this TYPE, but
1949 // do not act as though I can reach it"
1950 substs.upvar_tys.clone()
1951 }
1952
1953 // for `PhantomData<T>`, we pass `T`
1954 ty::TyStruct(def, substs) if def.is_phantom_data() => {
1955 substs.types.get_slice(TypeSpace).to_vec()
1956 }
1957
1958 ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => {
1959 def.all_fields()
1960 .map(|f| f.ty(self.tcx(), substs))
1961 .collect()
1962 }
1963 }
1964 }
1965
1966 fn collect_predicates_for_types(&mut self,
1967 obligation: &TraitObligation<'tcx>,
1968 trait_def_id: DefId,
1969 types: ty::Binder<Vec<Ty<'tcx>>>)
1970 -> Vec<PredicateObligation<'tcx>>
1971 {
1972 let derived_cause = match self.tcx().lang_items.to_builtin_kind(trait_def_id) {
1973 Some(_) => {
1974 self.derived_cause(obligation, BuiltinDerivedObligation)
1975 },
1976 None => {
1977 self.derived_cause(obligation, ImplDerivedObligation)
1978 }
1979 };
1980
1981 // Because the types were potentially derived from
1982 // higher-ranked obligations they may reference late-bound
1983 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
1984 // yield a type like `for<'a> &'a int`. In general, we
1985 // maintain the invariant that we never manipulate bound
1986 // regions, so we have to process these bound regions somehow.
1987 //
1988 // The strategy is to:
1989 //
1990 // 1. Instantiate those regions to skolemized regions (e.g.,
1991 // `for<'a> &'a int` becomes `&0 int`.
1992 // 2. Produce something like `&'0 int : Copy`
1993 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
1994
1995 // Move the binder into the individual types
1996 let bound_types: Vec<ty::Binder<Ty<'tcx>>> =
1997 types.skip_binder()
1998 .iter()
1999 .map(|&nested_ty| ty::Binder(nested_ty))
2000 .collect();
2001
2002 // For each type, produce a vector of resulting obligations
2003 let obligations: Result<Vec<Vec<_>>, _> = bound_types.iter().map(|nested_ty| {
2004 self.infcx.commit_if_ok(|snapshot| {
2005 let (skol_ty, skol_map) =
2006 self.infcx().skolemize_late_bound_regions(nested_ty, snapshot);
2007 let Normalized { value: normalized_ty, mut obligations } =
2008 project::normalize_with_depth(self,
2009 obligation.cause.clone(),
2010 obligation.recursion_depth + 1,
2011 &skol_ty);
2012 let skol_obligation =
2013 util::predicate_for_trait_def(self.tcx(),
2014 derived_cause.clone(),
2015 trait_def_id,
2016 obligation.recursion_depth + 1,
2017 normalized_ty,
2018 vec![]);
2019 obligations.push(skol_obligation);
2020 Ok(self.infcx().plug_leaks(skol_map, snapshot, &obligations))
2021 })
2022 }).collect();
2023
2024 // Flatten those vectors (couldn't do it above due `collect`)
2025 match obligations {
2026 Ok(obligations) => obligations.into_iter().flat_map(|o| o).collect(),
2027 Err(ErrorReported) => Vec::new(),
2028 }
2029 }
2030
2031 ///////////////////////////////////////////////////////////////////////////
2032 // CONFIRMATION
2033 //
2034 // Confirmation unifies the output type parameters of the trait
2035 // with the values found in the obligation, possibly yielding a
2036 // type error. See `README.md` for more details.
2037
2038 fn confirm_candidate(&mut self,
2039 obligation: &TraitObligation<'tcx>,
2040 candidate: SelectionCandidate<'tcx>)
2041 -> Result<Selection<'tcx>,SelectionError<'tcx>>
2042 {
2043 debug!("confirm_candidate({:?}, {:?})",
2044 obligation,
2045 candidate);
2046
2047 match candidate {
2048 BuiltinCandidate(builtin_bound) => {
2049 Ok(VtableBuiltin(
2050 self.confirm_builtin_candidate(obligation, builtin_bound)?))
2051 }
2052
2053 ParamCandidate(param) => {
2054 let obligations = self.confirm_param_candidate(obligation, param);
2055 Ok(VtableParam(obligations))
2056 }
2057
2058 DefaultImplCandidate(trait_def_id) => {
2059 let data = self.confirm_default_impl_candidate(obligation, trait_def_id);
2060 Ok(VtableDefaultImpl(data))
2061 }
2062
2063 DefaultImplObjectCandidate(trait_def_id) => {
2064 let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id);
2065 Ok(VtableDefaultImpl(data))
2066 }
2067
2068 ImplCandidate(impl_def_id) => {
2069 let vtable_impl =
2070 self.confirm_impl_candidate(obligation, impl_def_id)?;
2071 Ok(VtableImpl(vtable_impl))
2072 }
2073
2074 ClosureCandidate(closure_def_id, substs) => {
2075 let vtable_closure =
2076 self.confirm_closure_candidate(obligation, closure_def_id, substs)?;
2077 Ok(VtableClosure(vtable_closure))
2078 }
2079
2080 BuiltinObjectCandidate => {
2081 // This indicates something like `(Trait+Send) :
2082 // Send`. In this case, we know that this holds
2083 // because that's what the object type is telling us,
2084 // and there's really no additional obligations to
2085 // prove and no types in particular to unify etc.
2086 Ok(VtableParam(Vec::new()))
2087 }
2088
2089 ObjectCandidate => {
2090 let data = self.confirm_object_candidate(obligation);
2091 Ok(VtableObject(data))
2092 }
2093
2094 FnPointerCandidate => {
2095 let fn_type =
2096 self.confirm_fn_pointer_candidate(obligation)?;
2097 Ok(VtableFnPointer(fn_type))
2098 }
2099
2100 ProjectionCandidate => {
2101 self.confirm_projection_candidate(obligation);
2102 Ok(VtableParam(Vec::new()))
2103 }
2104
2105 BuiltinUnsizeCandidate => {
2106 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2107 Ok(VtableBuiltin(data))
2108 }
2109 }
2110 }
2111
2112 fn confirm_projection_candidate(&mut self,
2113 obligation: &TraitObligation<'tcx>)
2114 {
2115 let _: Result<(),()> =
2116 self.infcx.commit_if_ok(|snapshot| {
2117 let result =
2118 self.match_projection_obligation_against_bounds_from_trait(obligation,
2119 snapshot);
2120 assert!(result);
2121 Ok(())
2122 });
2123 }
2124
2125 fn confirm_param_candidate(&mut self,
2126 obligation: &TraitObligation<'tcx>,
2127 param: ty::PolyTraitRef<'tcx>)
2128 -> Vec<PredicateObligation<'tcx>>
2129 {
2130 debug!("confirm_param_candidate({:?},{:?})",
2131 obligation,
2132 param);
2133
2134 // During evaluation, we already checked that this
2135 // where-clause trait-ref could be unified with the obligation
2136 // trait-ref. Repeat that unification now without any
2137 // transactional boundary; it should not fail.
2138 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2139 Ok(obligations) => obligations,
2140 Err(()) => {
2141 bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
2142 param,
2143 obligation);
2144 }
2145 }
2146 }
2147
2148 fn confirm_builtin_candidate(&mut self,
2149 obligation: &TraitObligation<'tcx>,
2150 bound: ty::BuiltinBound)
2151 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2152 SelectionError<'tcx>>
2153 {
2154 debug!("confirm_builtin_candidate({:?})",
2155 obligation);
2156
2157 match self.builtin_bound(bound, obligation)? {
2158 If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)),
2159 AmbiguousBuiltin | ParameterBuiltin => {
2160 span_bug!(
2161 obligation.cause.span,
2162 "builtin bound for {:?} was ambig",
2163 obligation);
2164 }
2165 }
2166 }
2167
2168 fn vtable_builtin_data(&mut self,
2169 obligation: &TraitObligation<'tcx>,
2170 bound: ty::BuiltinBound,
2171 nested: ty::Binder<Vec<Ty<'tcx>>>)
2172 -> VtableBuiltinData<PredicateObligation<'tcx>>
2173 {
2174 debug!("vtable_builtin_data(obligation={:?}, bound={:?}, nested={:?})",
2175 obligation, bound, nested);
2176
2177 let trait_def = match self.tcx().lang_items.from_builtin_kind(bound) {
2178 Ok(def_id) => def_id,
2179 Err(_) => {
2180 bug!("builtin trait definition not found");
2181 }
2182 };
2183
2184 let obligations = self.collect_predicates_for_types(obligation, trait_def, nested);
2185
2186 debug!("vtable_builtin_data: obligations={:?}",
2187 obligations);
2188
2189 VtableBuiltinData { nested: obligations }
2190 }
2191
2192 /// This handles the case where a `impl Foo for ..` impl is being used.
2193 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2194 ///
2195 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2196 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2197 fn confirm_default_impl_candidate(&mut self,
2198 obligation: &TraitObligation<'tcx>,
2199 trait_def_id: DefId)
2200 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2201 {
2202 debug!("confirm_default_impl_candidate({:?}, {:?})",
2203 obligation,
2204 trait_def_id);
2205
2206 // binder is moved below
2207 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2208 let types = self.constituent_types_for_ty(self_ty);
2209 self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types))
2210 }
2211
2212 fn confirm_default_impl_object_candidate(&mut self,
2213 obligation: &TraitObligation<'tcx>,
2214 trait_def_id: DefId)
2215 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2216 {
2217 debug!("confirm_default_impl_object_candidate({:?}, {:?})",
2218 obligation,
2219 trait_def_id);
2220
2221 assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like"));
2222
2223 // OK to skip binder, it is reintroduced below
2224 let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
2225 match self_ty.sty {
2226 ty::TyTrait(ref data) => {
2227 // OK to skip the binder, it is reintroduced below
2228 let input_types = data.principal.skip_binder().substs.types.get_slice(TypeSpace);
2229 let assoc_types = data.bounds.projection_bounds
2230 .iter()
2231 .map(|pb| pb.skip_binder().ty);
2232 let all_types: Vec<_> = input_types.iter().cloned()
2233 .chain(assoc_types)
2234 .collect();
2235
2236 // reintroduce the two binding levels we skipped, then flatten into one
2237 let all_types = ty::Binder(ty::Binder(all_types));
2238 let all_types = self.tcx().flatten_late_bound_regions(&all_types);
2239
2240 self.vtable_default_impl(obligation, trait_def_id, all_types)
2241 }
2242 _ => {
2243 bug!("asked to confirm default object implementation for non-object type: {:?}",
2244 self_ty);
2245 }
2246 }
2247 }
2248
2249 /// See `confirm_default_impl_candidate`
2250 fn vtable_default_impl(&mut self,
2251 obligation: &TraitObligation<'tcx>,
2252 trait_def_id: DefId,
2253 nested: ty::Binder<Vec<Ty<'tcx>>>)
2254 -> VtableDefaultImplData<PredicateObligation<'tcx>>
2255 {
2256 debug!("vtable_default_impl_data: nested={:?}", nested);
2257
2258 let mut obligations = self.collect_predicates_for_types(obligation,
2259 trait_def_id,
2260 nested);
2261
2262 let trait_obligations: Result<Vec<_>,()> = self.infcx.commit_if_ok(|snapshot| {
2263 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
2264 let (trait_ref, skol_map) =
2265 self.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot);
2266 Ok(self.impl_or_trait_obligations(obligation.cause.clone(),
2267 obligation.recursion_depth + 1,
2268 trait_def_id,
2269 &trait_ref.substs,
2270 skol_map,
2271 snapshot))
2272 });
2273
2274 // no Errors in that code above
2275 obligations.append(&mut trait_obligations.unwrap());
2276
2277 debug!("vtable_default_impl_data: obligations={:?}", obligations);
2278
2279 VtableDefaultImplData {
2280 trait_def_id: trait_def_id,
2281 nested: obligations
2282 }
2283 }
2284
2285 fn confirm_impl_candidate(&mut self,
2286 obligation: &TraitObligation<'tcx>,
2287 impl_def_id: DefId)
2288 -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>,
2289 SelectionError<'tcx>>
2290 {
2291 debug!("confirm_impl_candidate({:?},{:?})",
2292 obligation,
2293 impl_def_id);
2294
2295 // First, create the substitutions by matching the impl again,
2296 // this time not in a probe.
2297 self.infcx.commit_if_ok(|snapshot| {
2298 let (substs, skol_map) =
2299 self.rematch_impl(impl_def_id, obligation,
2300 snapshot);
2301 debug!("confirm_impl_candidate substs={:?}", substs);
2302 Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(),
2303 obligation.recursion_depth + 1, skol_map, snapshot))
2304 })
2305 }
2306
2307 fn vtable_impl(&mut self,
2308 impl_def_id: DefId,
2309 mut substs: Normalized<'tcx, Substs<'tcx>>,
2310 cause: ObligationCause<'tcx>,
2311 recursion_depth: usize,
2312 skol_map: infer::SkolemizationMap,
2313 snapshot: &infer::CombinedSnapshot)
2314 -> VtableImplData<'tcx, PredicateObligation<'tcx>>
2315 {
2316 debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
2317 impl_def_id,
2318 substs,
2319 recursion_depth,
2320 skol_map);
2321
2322 let mut impl_obligations =
2323 self.impl_or_trait_obligations(cause,
2324 recursion_depth,
2325 impl_def_id,
2326 &substs.value,
2327 skol_map,
2328 snapshot);
2329
2330 debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
2331 impl_def_id,
2332 impl_obligations);
2333
2334 // Because of RFC447, the impl-trait-ref and obligations
2335 // are sufficient to determine the impl substs, without
2336 // relying on projections in the impl-trait-ref.
2337 //
2338 // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
2339 impl_obligations.append(&mut substs.obligations);
2340
2341 VtableImplData { impl_def_id: impl_def_id,
2342 substs: self.tcx().mk_substs(substs.value),
2343 nested: impl_obligations }
2344 }
2345
2346 fn confirm_object_candidate(&mut self,
2347 obligation: &TraitObligation<'tcx>)
2348 -> VtableObjectData<'tcx>
2349 {
2350 debug!("confirm_object_candidate({:?})",
2351 obligation);
2352
2353 // FIXME skipping binder here seems wrong -- we should
2354 // probably flatten the binder from the obligation and the
2355 // binder from the object. Have to try to make a broken test
2356 // case that results. -nmatsakis
2357 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2358 let poly_trait_ref = match self_ty.sty {
2359 ty::TyTrait(ref data) => {
2360 data.principal_trait_ref_with_self_ty(self.tcx(), self_ty)
2361 }
2362 _ => {
2363 span_bug!(obligation.cause.span,
2364 "object candidate with non-object");
2365 }
2366 };
2367
2368 let mut upcast_trait_ref = None;
2369 let vtable_base;
2370
2371 {
2372 // We want to find the first supertrait in the list of
2373 // supertraits that we can unify with, and do that
2374 // unification. We know that there is exactly one in the list
2375 // where we can unify because otherwise select would have
2376 // reported an ambiguity. (When we do find a match, also
2377 // record it for later.)
2378 let nonmatching =
2379 util::supertraits(self.tcx(), poly_trait_ref)
2380 .take_while(|&t| {
2381 match
2382 self.infcx.commit_if_ok(
2383 |_| self.match_poly_trait_ref(obligation, t))
2384 {
2385 Ok(_) => { upcast_trait_ref = Some(t); false }
2386 Err(_) => { true }
2387 }
2388 });
2389
2390 // Additionally, for each of the nonmatching predicates that
2391 // we pass over, we sum up the set of number of vtable
2392 // entries, so that we can compute the offset for the selected
2393 // trait.
2394 vtable_base =
2395 nonmatching.map(|t| util::count_own_vtable_entries(self.tcx(), t))
2396 .sum();
2397
2398 }
2399
2400 VtableObjectData {
2401 upcast_trait_ref: upcast_trait_ref.unwrap(),
2402 vtable_base: vtable_base,
2403 }
2404 }
2405
2406 fn confirm_fn_pointer_candidate(&mut self,
2407 obligation: &TraitObligation<'tcx>)
2408 -> Result<ty::Ty<'tcx>,SelectionError<'tcx>>
2409 {
2410 debug!("confirm_fn_pointer_candidate({:?})",
2411 obligation);
2412
2413 // ok to skip binder; it is reintroduced below
2414 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
2415 let sig = self_ty.fn_sig();
2416 let trait_ref =
2417 util::closure_trait_ref_and_return_type(self.tcx(),
2418 obligation.predicate.def_id(),
2419 self_ty,
2420 sig,
2421 util::TupleArgumentsFlag::Yes)
2422 .map_bound(|(trait_ref, _)| trait_ref);
2423
2424 self.confirm_poly_trait_refs(obligation.cause.clone(),
2425 obligation.predicate.to_poly_trait_ref(),
2426 trait_ref)?;
2427 Ok(self_ty)
2428 }
2429
2430 fn confirm_closure_candidate(&mut self,
2431 obligation: &TraitObligation<'tcx>,
2432 closure_def_id: DefId,
2433 substs: &ty::ClosureSubsts<'tcx>)
2434 -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
2435 SelectionError<'tcx>>
2436 {
2437 debug!("confirm_closure_candidate({:?},{:?},{:?})",
2438 obligation,
2439 closure_def_id,
2440 substs);
2441
2442 let Normalized {
2443 value: trait_ref,
2444 obligations
2445 } = self.closure_trait_ref(obligation, closure_def_id, substs);
2446
2447 debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
2448 closure_def_id,
2449 trait_ref,
2450 obligations);
2451
2452 self.confirm_poly_trait_refs(obligation.cause.clone(),
2453 obligation.predicate.to_poly_trait_ref(),
2454 trait_ref)?;
2455
2456 Ok(VtableClosureData {
2457 closure_def_id: closure_def_id,
2458 substs: substs.clone(),
2459 nested: obligations
2460 })
2461 }
2462
2463 /// In the case of closure types and fn pointers,
2464 /// we currently treat the input type parameters on the trait as
2465 /// outputs. This means that when we have a match we have only
2466 /// considered the self type, so we have to go back and make sure
2467 /// to relate the argument types too. This is kind of wrong, but
2468 /// since we control the full set of impls, also not that wrong,
2469 /// and it DOES yield better error messages (since we don't report
2470 /// errors as if there is no applicable impl, but rather report
2471 /// errors are about mismatched argument types.
2472 ///
2473 /// Here is an example. Imagine we have a closure expression
2474 /// and we desugared it so that the type of the expression is
2475 /// `Closure`, and `Closure` expects an int as argument. Then it
2476 /// is "as if" the compiler generated this impl:
2477 ///
2478 /// impl Fn(int) for Closure { ... }
2479 ///
2480 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
2481 /// we have matched the self-type `Closure`. At this point we'll
2482 /// compare the `int` to `usize` and generate an error.
2483 ///
2484 /// Note that this checking occurs *after* the impl has selected,
2485 /// because these output type parameters should not affect the
2486 /// selection of the impl. Therefore, if there is a mismatch, we
2487 /// report an error to the user.
2488 fn confirm_poly_trait_refs(&mut self,
2489 obligation_cause: ObligationCause,
2490 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
2491 expected_trait_ref: ty::PolyTraitRef<'tcx>)
2492 -> Result<(), SelectionError<'tcx>>
2493 {
2494 let origin = TypeOrigin::RelateOutputImplTypes(obligation_cause.span);
2495
2496 let obligation_trait_ref = obligation_trait_ref.clone();
2497 self.infcx.sub_poly_trait_refs(false,
2498 origin,
2499 expected_trait_ref.clone(),
2500 obligation_trait_ref.clone())
2501 // FIXME(#32730) propagate obligations
2502 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
2503 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
2504 }
2505
2506 fn confirm_builtin_unsize_candidate(&mut self,
2507 obligation: &TraitObligation<'tcx>,)
2508 -> Result<VtableBuiltinData<PredicateObligation<'tcx>>,
2509 SelectionError<'tcx>> {
2510 let tcx = self.tcx();
2511
2512 // assemble_candidates_for_unsizing should ensure there are no late bound
2513 // regions here. See the comment there for more details.
2514 let source = self.infcx.shallow_resolve(
2515 tcx.no_late_bound_regions(&obligation.self_ty()).unwrap());
2516 let target = self.infcx.shallow_resolve(obligation.predicate.0.input_types()[0]);
2517
2518 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
2519 source, target);
2520
2521 let mut nested = vec![];
2522 match (&source.sty, &target.sty) {
2523 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2524 (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => {
2525 // See assemble_candidates_for_unsizing for more info.
2526 let bounds = ty::ExistentialBounds {
2527 region_bound: data_b.bounds.region_bound,
2528 builtin_bounds: data_b.bounds.builtin_bounds,
2529 projection_bounds: data_a.bounds.projection_bounds.clone(),
2530 };
2531
2532 let new_trait = tcx.mk_trait(data_a.principal.clone(), bounds);
2533 let origin = TypeOrigin::Misc(obligation.cause.span);
2534 let InferOk { obligations, .. } =
2535 self.infcx.sub_types(false, origin, new_trait, target)
2536 .map_err(|_| Unimplemented)?;
2537 // FIXME(#32730) propagate obligations
2538 assert!(obligations.is_empty());
2539
2540 // Register one obligation for 'a: 'b.
2541 let cause = ObligationCause::new(obligation.cause.span,
2542 obligation.cause.body_id,
2543 ObjectCastObligation(target));
2544 let outlives = ty::OutlivesPredicate(data_a.bounds.region_bound,
2545 data_b.bounds.region_bound);
2546 nested.push(Obligation::with_depth(cause,
2547 obligation.recursion_depth + 1,
2548 ty::Binder(outlives).to_predicate()));
2549 }
2550
2551 // T -> Trait.
2552 (_, &ty::TyTrait(ref data)) => {
2553 let object_did = data.principal_def_id();
2554 if !object_safety::is_object_safe(tcx, object_did) {
2555 return Err(TraitNotObjectSafe(object_did));
2556 }
2557
2558 let cause = ObligationCause::new(obligation.cause.span,
2559 obligation.cause.body_id,
2560 ObjectCastObligation(target));
2561 let mut push = |predicate| {
2562 nested.push(Obligation::with_depth(cause.clone(),
2563 obligation.recursion_depth + 1,
2564 predicate));
2565 };
2566
2567 // Create the obligation for casting from T to Trait.
2568 push(data.principal_trait_ref_with_self_ty(tcx, source).to_predicate());
2569
2570 // We can only make objects from sized types.
2571 let mut builtin_bounds = data.bounds.builtin_bounds;
2572 builtin_bounds.insert(ty::BoundSized);
2573
2574 // Create additional obligations for all the various builtin
2575 // bounds attached to the object cast. (In other words, if the
2576 // object type is Foo+Send, this would create an obligation
2577 // for the Send check.)
2578 for bound in &builtin_bounds {
2579 if let Ok(tr) = util::trait_ref_for_builtin_bound(tcx, bound, source) {
2580 push(tr.to_predicate());
2581 } else {
2582 return Err(Unimplemented);
2583 }
2584 }
2585
2586 // Create obligations for the projection predicates.
2587 for bound in data.projection_bounds_with_self_ty(tcx, source) {
2588 push(bound.to_predicate());
2589 }
2590
2591 // If the type is `Foo+'a`, ensures that the type
2592 // being cast to `Foo+'a` outlives `'a`:
2593 let outlives = ty::OutlivesPredicate(source,
2594 data.bounds.region_bound);
2595 push(ty::Binder(outlives).to_predicate());
2596 }
2597
2598 // [T; n] -> [T].
2599 (&ty::TyArray(a, _), &ty::TySlice(b)) => {
2600 let origin = TypeOrigin::Misc(obligation.cause.span);
2601 let InferOk { obligations, .. } =
2602 self.infcx.sub_types(false, origin, a, b)
2603 .map_err(|_| Unimplemented)?;
2604 // FIXME(#32730) propagate obligations
2605 assert!(obligations.is_empty());
2606 }
2607
2608 // Struct<T> -> Struct<U>.
2609 (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => {
2610 let fields = def
2611 .all_fields()
2612 .map(|f| f.unsubst_ty())
2613 .collect::<Vec<_>>();
2614
2615 // The last field of the structure has to exist and contain type parameters.
2616 let field = if let Some(&field) = fields.last() {
2617 field
2618 } else {
2619 return Err(Unimplemented);
2620 };
2621 let mut ty_params = vec![];
2622 for ty in field.walk() {
2623 if let ty::TyParam(p) = ty.sty {
2624 assert!(p.space == TypeSpace);
2625 let idx = p.idx as usize;
2626 if !ty_params.contains(&idx) {
2627 ty_params.push(idx);
2628 }
2629 }
2630 }
2631 if ty_params.is_empty() {
2632 return Err(Unimplemented);
2633 }
2634
2635 // Replace type parameters used in unsizing with
2636 // TyError and ensure they do not affect any other fields.
2637 // This could be checked after type collection for any struct
2638 // with a potentially unsized trailing field.
2639 let mut new_substs = substs_a.clone();
2640 for &i in &ty_params {
2641 new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err;
2642 }
2643 for &ty in fields.split_last().unwrap().1 {
2644 if ty.subst(tcx, &new_substs).references_error() {
2645 return Err(Unimplemented);
2646 }
2647 }
2648
2649 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
2650 let inner_source = field.subst(tcx, substs_a);
2651 let inner_target = field.subst(tcx, substs_b);
2652
2653 // Check that the source structure with the target's
2654 // type parameters is a subtype of the target.
2655 for &i in &ty_params {
2656 let param_b = *substs_b.types.get(TypeSpace, i);
2657 new_substs.types.get_mut_slice(TypeSpace)[i] = param_b;
2658 }
2659 let new_struct = tcx.mk_struct(def, tcx.mk_substs(new_substs));
2660 let origin = TypeOrigin::Misc(obligation.cause.span);
2661 let InferOk { obligations, .. } =
2662 self.infcx.sub_types(false, origin, new_struct, target)
2663 .map_err(|_| Unimplemented)?;
2664 // FIXME(#32730) propagate obligations
2665 assert!(obligations.is_empty());
2666
2667 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
2668 nested.push(util::predicate_for_trait_def(tcx,
2669 obligation.cause.clone(),
2670 obligation.predicate.def_id(),
2671 obligation.recursion_depth + 1,
2672 inner_source,
2673 vec![inner_target]));
2674 }
2675
2676 _ => bug!()
2677 };
2678
2679 Ok(VtableBuiltinData { nested: nested })
2680 }
2681
2682 ///////////////////////////////////////////////////////////////////////////
2683 // Matching
2684 //
2685 // Matching is a common path used for both evaluation and
2686 // confirmation. It basically unifies types that appear in impls
2687 // and traits. This does affect the surrounding environment;
2688 // therefore, when used during evaluation, match routines must be
2689 // run inside of a `probe()` so that their side-effects are
2690 // contained.
2691
2692 fn rematch_impl(&mut self,
2693 impl_def_id: DefId,
2694 obligation: &TraitObligation<'tcx>,
2695 snapshot: &infer::CombinedSnapshot)
2696 -> (Normalized<'tcx, Substs<'tcx>>, infer::SkolemizationMap)
2697 {
2698 match self.match_impl(impl_def_id, obligation, snapshot) {
2699 Ok((substs, skol_map)) => (substs, skol_map),
2700 Err(()) => {
2701 bug!("Impl {:?} was matchable against {:?} but now is not",
2702 impl_def_id,
2703 obligation);
2704 }
2705 }
2706 }
2707
2708 fn match_impl(&mut self,
2709 impl_def_id: DefId,
2710 obligation: &TraitObligation<'tcx>,
2711 snapshot: &infer::CombinedSnapshot)
2712 -> Result<(Normalized<'tcx, Substs<'tcx>>,
2713 infer::SkolemizationMap), ()>
2714 {
2715 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
2716
2717 // Before we create the substitutions and everything, first
2718 // consider a "quick reject". This avoids creating more types
2719 // and so forth that we need to.
2720 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
2721 return Err(());
2722 }
2723
2724 let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
2725 &obligation.predicate,
2726 snapshot);
2727 let skol_obligation_trait_ref = skol_obligation.trait_ref;
2728
2729 let impl_substs = util::fresh_type_vars_for_impl(self.infcx,
2730 obligation.cause.span,
2731 impl_def_id);
2732
2733 let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
2734 &impl_substs);
2735
2736 let impl_trait_ref =
2737 project::normalize_with_depth(self,
2738 obligation.cause.clone(),
2739 obligation.recursion_depth + 1,
2740 &impl_trait_ref);
2741
2742 debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
2743 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
2744 impl_def_id,
2745 obligation,
2746 impl_trait_ref,
2747 skol_obligation_trait_ref);
2748
2749 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2750 let InferOk { obligations, .. } =
2751 self.infcx.eq_trait_refs(false,
2752 origin,
2753 impl_trait_ref.value.clone(),
2754 skol_obligation_trait_ref)
2755 .map_err(|e| {
2756 debug!("match_impl: failed eq_trait_refs due to `{}`", e);
2757 ()
2758 })?;
2759 // FIXME(#32730) propagate obligations
2760 assert!(obligations.is_empty());
2761
2762 if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) {
2763 debug!("match_impl: failed leak check due to `{}`", e);
2764 return Err(());
2765 }
2766
2767 debug!("match_impl: success impl_substs={:?}", impl_substs);
2768 Ok((Normalized {
2769 value: impl_substs,
2770 obligations: impl_trait_ref.obligations
2771 }, skol_map))
2772 }
2773
2774 fn fast_reject_trait_refs(&mut self,
2775 obligation: &TraitObligation,
2776 impl_trait_ref: &ty::TraitRef)
2777 -> bool
2778 {
2779 // We can avoid creating type variables and doing the full
2780 // substitution if we find that any of the input types, when
2781 // simplified, do not match.
2782
2783 obligation.predicate.0.input_types().iter()
2784 .zip(impl_trait_ref.input_types())
2785 .any(|(&obligation_ty, &impl_ty)| {
2786 let simplified_obligation_ty =
2787 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
2788 let simplified_impl_ty =
2789 fast_reject::simplify_type(self.tcx(), impl_ty, false);
2790
2791 simplified_obligation_ty.is_some() &&
2792 simplified_impl_ty.is_some() &&
2793 simplified_obligation_ty != simplified_impl_ty
2794 })
2795 }
2796
2797 /// Normalize `where_clause_trait_ref` and try to match it against
2798 /// `obligation`. If successful, return any predicates that
2799 /// result from the normalization. Normalization is necessary
2800 /// because where-clauses are stored in the parameter environment
2801 /// unnormalized.
2802 fn match_where_clause_trait_ref(&mut self,
2803 obligation: &TraitObligation<'tcx>,
2804 where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
2805 -> Result<Vec<PredicateObligation<'tcx>>,()>
2806 {
2807 self.match_poly_trait_ref(obligation, where_clause_trait_ref)?;
2808 Ok(Vec::new())
2809 }
2810
2811 /// Returns `Ok` if `poly_trait_ref` being true implies that the
2812 /// obligation is satisfied.
2813 fn match_poly_trait_ref(&self,
2814 obligation: &TraitObligation<'tcx>,
2815 poly_trait_ref: ty::PolyTraitRef<'tcx>)
2816 -> Result<(),()>
2817 {
2818 debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
2819 obligation,
2820 poly_trait_ref);
2821
2822 let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span);
2823 self.infcx.sub_poly_trait_refs(false,
2824 origin,
2825 poly_trait_ref,
2826 obligation.predicate.to_poly_trait_ref())
2827 // FIXME(#32730) propagate obligations
2828 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
2829 .map_err(|_| ())
2830 }
2831
2832 ///////////////////////////////////////////////////////////////////////////
2833 // Miscellany
2834
2835 fn match_fresh_trait_refs(&self,
2836 previous: &ty::PolyTraitRef<'tcx>,
2837 current: &ty::PolyTraitRef<'tcx>)
2838 -> bool
2839 {
2840 let mut matcher = ty::_match::Match::new(self.tcx());
2841 matcher.relate(previous, current).is_ok()
2842 }
2843
2844 fn push_stack<'o,'s:'o>(&mut self,
2845 previous_stack: TraitObligationStackList<'s, 'tcx>,
2846 obligation: &'o TraitObligation<'tcx>)
2847 -> TraitObligationStack<'o, 'tcx>
2848 {
2849 let fresh_trait_ref =
2850 obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
2851
2852 TraitObligationStack {
2853 obligation: obligation,
2854 fresh_trait_ref: fresh_trait_ref,
2855 previous: previous_stack,
2856 }
2857 }
2858
2859 fn closure_trait_ref_unnormalized(&mut self,
2860 obligation: &TraitObligation<'tcx>,
2861 closure_def_id: DefId,
2862 substs: &ty::ClosureSubsts<'tcx>)
2863 -> ty::PolyTraitRef<'tcx>
2864 {
2865 let closure_type = self.infcx.closure_type(closure_def_id, substs);
2866 let ty::Binder((trait_ref, _)) =
2867 util::closure_trait_ref_and_return_type(self.tcx(),
2868 obligation.predicate.def_id(),
2869 obligation.predicate.0.self_ty(), // (1)
2870 &closure_type.sig,
2871 util::TupleArgumentsFlag::No);
2872 // (1) Feels icky to skip the binder here, but OTOH we know
2873 // that the self-type is an unboxed closure type and hence is
2874 // in fact unparameterized (or at least does not reference any
2875 // regions bound in the obligation). Still probably some
2876 // refactoring could make this nicer.
2877
2878 ty::Binder(trait_ref)
2879 }
2880
2881 fn closure_trait_ref(&mut self,
2882 obligation: &TraitObligation<'tcx>,
2883 closure_def_id: DefId,
2884 substs: &ty::ClosureSubsts<'tcx>)
2885 -> Normalized<'tcx, ty::PolyTraitRef<'tcx>>
2886 {
2887 let trait_ref = self.closure_trait_ref_unnormalized(
2888 obligation, closure_def_id, substs);
2889
2890 // A closure signature can contain associated types which
2891 // must be normalized.
2892 normalize_with_depth(self,
2893 obligation.cause.clone(),
2894 obligation.recursion_depth+1,
2895 &trait_ref)
2896 }
2897
2898 /// Returns the obligations that are implied by instantiating an
2899 /// impl or trait. The obligations are substituted and fully
2900 /// normalized. This is used when confirming an impl or default
2901 /// impl.
2902 fn impl_or_trait_obligations(&mut self,
2903 cause: ObligationCause<'tcx>,
2904 recursion_depth: usize,
2905 def_id: DefId, // of impl or trait
2906 substs: &Substs<'tcx>, // for impl or trait
2907 skol_map: infer::SkolemizationMap,
2908 snapshot: &infer::CombinedSnapshot)
2909 -> Vec<PredicateObligation<'tcx>>
2910 {
2911 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
2912 let tcx = self.tcx();
2913
2914 // To allow for one-pass evaluation of the nested obligation,
2915 // each predicate must be preceded by the obligations required
2916 // to normalize it.
2917 // for example, if we have:
2918 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
2919 // the impl will have the following predicates:
2920 // <V as Iterator>::Item = U,
2921 // U: Iterator, U: Sized,
2922 // V: Iterator, V: Sized,
2923 // <U as Iterator>::Item: Copy
2924 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
2925 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
2926 // `$1: Copy`, so we must ensure the obligations are emitted in
2927 // that order.
2928 let predicates = tcx
2929 .lookup_predicates(def_id)
2930 .predicates.iter()
2931 .flat_map(|predicate| {
2932 let predicate =
2933 normalize_with_depth(self, cause.clone(), recursion_depth,
2934 &predicate.subst(tcx, substs));
2935 predicate.obligations.into_iter().chain(
2936 Some(Obligation {
2937 cause: cause.clone(),
2938 recursion_depth: recursion_depth,
2939 predicate: predicate.value
2940 }))
2941 }).collect();
2942 self.infcx().plug_leaks(skol_map, snapshot, &predicates)
2943 }
2944
2945 #[allow(unused_comparisons)]
2946 fn derived_cause(&self,
2947 obligation: &TraitObligation<'tcx>,
2948 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
2949 -> ObligationCause<'tcx>
2950 {
2951 /*!
2952 * Creates a cause for obligations that are derived from
2953 * `obligation` by a recursive search (e.g., for a builtin
2954 * bound, or eventually a `impl Foo for ..`). If `obligation`
2955 * is itself a derived obligation, this is just a clone, but
2956 * otherwise we create a "derived obligation" cause so as to
2957 * keep track of the original root obligation for error
2958 * reporting.
2959 */
2960
2961 // NOTE(flaper87): As of now, it keeps track of the whole error
2962 // chain. Ideally, we should have a way to configure this either
2963 // by using -Z verbose or just a CLI argument.
2964 if obligation.recursion_depth >= 0 {
2965 let derived_cause = DerivedObligationCause {
2966 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
2967 parent_code: Rc::new(obligation.cause.code.clone())
2968 };
2969 let derived_code = variant(derived_cause);
2970 ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
2971 } else {
2972 obligation.cause.clone()
2973 }
2974 }
2975 }
2976
2977 impl<'tcx> SelectionCache<'tcx> {
2978 pub fn new() -> SelectionCache<'tcx> {
2979 SelectionCache {
2980 hashmap: RefCell::new(FnvHashMap())
2981 }
2982 }
2983 }
2984
2985 impl<'tcx> EvaluationCache<'tcx> {
2986 pub fn new() -> EvaluationCache<'tcx> {
2987 EvaluationCache {
2988 hashmap: RefCell::new(FnvHashMap())
2989 }
2990 }
2991 }
2992
2993 impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
2994 fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
2995 TraitObligationStackList::with(self)
2996 }
2997
2998 fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
2999 self.list()
3000 }
3001 }
3002
3003 #[derive(Copy, Clone)]
3004 struct TraitObligationStackList<'o,'tcx:'o> {
3005 head: Option<&'o TraitObligationStack<'o,'tcx>>
3006 }
3007
3008 impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
3009 fn empty() -> TraitObligationStackList<'o,'tcx> {
3010 TraitObligationStackList { head: None }
3011 }
3012
3013 fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
3014 TraitObligationStackList { head: Some(r) }
3015 }
3016 }
3017
3018 impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
3019 type Item = &'o TraitObligationStack<'o,'tcx>;
3020
3021 fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
3022 match self.head {
3023 Some(o) => {
3024 *self = o.previous;
3025 Some(o)
3026 }
3027 None => None
3028 }
3029 }
3030 }
3031
3032 impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
3033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3034 write!(f, "TraitObligationStack({:?})", self.obligation)
3035 }
3036 }
3037
3038 impl EvaluationResult {
3039 fn may_apply(&self) -> bool {
3040 match *self {
3041 EvaluatedToOk |
3042 EvaluatedToAmbig |
3043 EvaluatedToUnknown => true,
3044
3045 EvaluatedToErr => false
3046 }
3047 }
3048 }
3049
3050 impl MethodMatchResult {
3051 pub fn may_apply(&self) -> bool {
3052 match *self {
3053 MethodMatched(_) => true,
3054 MethodAmbiguous(_) => true,
3055 MethodDidNotMatch => false,
3056 }
3057 }
3058 }