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